c 读取文件并把读取胡内容放到一个字符串中
以下是一个例子:
#include <stdio.h>
int main() {
FILE *fp;
char file_content[1000];
fp = fopen("example.txt", "r"); // 打开文件 example.txt
if (fp == NULL) {
printf("无法打开文件\n");
return 1;
}
fgets(file_content, 1000, fp); // 从文件中读取内容
printf("文件内容:%s", file_content);
fclose(fp); // 关闭文件
return 0;
}
上述代码中,我们使用了 fopen() 函数打开了一个文件,并将其赋值给 fp 变量。然后,我们使用 fgets() 函数从文件中读取了内容,并将其存储在 file_content 字符数组中。最后,我们使用 printf() 函数输出了读取到的文件内容。
需要注意的是,fgets() 函数读取的内容会包含换行符。如果不需要换行符,可以使用字符串处理函数 strtok() 或者 strcspn() 去除。
原文地址: https://www.cveoy.top/t/topic/bSC6 著作权归作者所有。请勿转载和采集!