c - 将文件的全部内容读入 c char *,包括新行

标签 c io

我正在寻找一个跨平台(Windows + Linux)解决方案来将整个文件的内容读入 char *

这是我现在得到的:

FILE *stream;
char *contents;
fileSize = 0;

//Open the stream
stream = fopen(argv[1], "r");

//Steak to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);

//Allocate enough memory (should I add 1 for the \0?)
contents = (char *)malloc(fileSize);

//Read the file 
fscanf(stream, "%s", contents);     

//Print it again for debugging
printf("Read %s\n", contents);

不幸的是,这只会打印文件中的第一行,所以我假设 fscanf 在第一个换行符处停止。但是我想阅读整个文件,包括并保留换行符。我不想使用 while 循环和 realloc 来手动构造整个字符串,我的意思是必须有更简单的方法吗?

最佳答案

可能是这样的?

FILE *stream;
char *contents;
fileSize = 0;

//Open the stream. Note "b" to avoid DOS/UNIX new line conversion.
stream = fopen(argv[1], "rb");

//Seek to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);

//Allocate enough memory (add 1 for the \0, since fread won't add it)
contents = malloc(fileSize+1);

//Read the file 
size_t size=fread(contents,1,fileSize,stream);
contents[size]=0; // Add terminating zero.

//Print it again for debugging
printf("Read %s\n", contents);

//Close the file
fclose(stream);
free(contents);

关于c - 将文件的全部内容读入 c char *,包括新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11793689/

相关文章:

java - 成功实现了线程,但我不知道如何将结果写入文件

c - C语言中%25d是什么意思

c++ - 在 Windows 上获取 C\C++ 中的所有环境变量

java - 使用java测量磁盘写入/读取速度

java - JVM崩溃时如何处理内存数据?

c - C以字符数组和打印形式存储矩阵

c - 夹板警告 "Statement has no effect"由于函数指针

c - 在 Cortex R5 上快速输出用户数据

c - 在 C 中为结构内的指针分配和分配内存?

java - 使用 java 集合对 Person 的 ArrayList 进行排序