读取文件的全部内容到c的char *,包括新线 [英] Read the entire contents of a file to c char *, including new lines
本文介绍了读取文件的全部内容到c的char *,包括新线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在找一个跨平台(Windows + Linux)的解决方案,以读取整个文件的内容到的char *
。
I'm looking for a cross platform (Windows + Linux) solution to reading the contents of an entire file into a 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停在第一个换行符。不过,我想读取整个文件包括,和preserving,新行字符。我想preFER不使用while循环和realloc手动构建整个字符串,我的意思是,必须有一个简单的方法?
Unfortunately this will only print the first line in the file so I assume that fscanf stops at the first newline character. However I would like to read the entire file including, and preserving, the new line characters. I'd prefer not to use a while loop and realloc to manually construct the entire string, I mean there has to be a simpler way?
推荐答案
这样的事情,可能是?
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的char *,包括新线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文