1

我正在寻找一种跨平台(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 来手动构造整个字符串,我的意思是必须有一个更简单的方法?

4

4 回答 4

5

像这样的东西,可能是?

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);
于 2012-08-03T10:21:14.237 回答
0

该函数fread将从流中读取并且不会在行尾字符处终止。

man页面中,您有:

size_t fread(void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);

读取大小为 size的nitems

于 2012-08-03T10:16:19.703 回答
0

fread按原样读取所有文件:

 if (fread(contents, 1, fileSize, stream) != fileSize) {
    /* error occurred */
 }
于 2012-08-03T10:16:51.857 回答
0

我有这个:

ssize_t filetomem(const char *filename, uint8_t **result)
{ 
    ssize_t size = 0;
    FILE *f = fopen(filename, "r");
    if (f == NULL) 
    { 
        *result = NULL;
        return -1;
    } 
    fseek(f, 0, SEEK_END);
    size = ftell(f);
    fseek(f, 0, SEEK_SET);
    *result = malloc(size);
    if (size != fread(*result, sizeof(**result), size, f)) 
    { 
        free(*result);
        return -2;
    } 

    fclose(f);
    return size;
}

返回值含义:

  • 正数或0:成功读取文件
  • 减一:无法打开文件(可能没有这样的文件)
  • 减二:fread() 失败
于 2012-08-03T10:17:50.507 回答