C语言 如何将整个文件加载到 C 中的字符串中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7856741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:57:49  来源:igfitidea点击:

How can I load a whole file into a string in C

cstringfile

提问by rahmu

Possible Duplicate:
Easiest way to get file's contents in C

可能的重复:
在 C 中获取文件内容的最简单方法

My program reads files that span over many lines. I would like to hold the content of a file in a single string.

我的程序读取跨越多行的文件。我想将文件的内容保存在一个字符串中。

I don't know the number of lines of my file before execution, however I have fixed a line size to MAX_LINE_LEN.

我不知道执行前文件的行数,但是我已将行大小固定为 MAX_LINE_LEN。

How can you do that?

你怎么能这样做?

回答by Dennis

The function fread()doesn't care about line breaks. The following code reads the contents of input_file_nameand saves them to the array file_contents:

该函数fread()不关心换行符。以下代码读取 的内容input_file_name并将其保存到数组中file_contents

char *file_contents;
long input_file_size;
FILE *input_file = fopen(input_file_name, "rb");
fseek(input_file, 0, SEEK_END);
input_file_size = ftell(input_file);
rewind(input_file);
file_contents = malloc(input_file_size * (sizeof(char)));
fread(file_contents, sizeof(char), input_file_size, input_file);
fclose(input_file);

You can only make a string of this array if input_file_namecontains the \0character. If it does not, change the last three lines to:

如果input_file_name包含\0字符,则只能创建此数组的字符串。如果没有,请将最后三行更改为:

file_contents = malloc((input_file_size + 1) * (sizeof(char)));
fread(file_contents, sizeof(char), input_file_size, input_file);
fclose(input_file);
file_contents[input_file_size] = 0;

回答by James

1) figure out the size of the file with fstat.

1) 用fstat.

2) alloc a zeroed buffer of this length + 1

2) 分配一个此长度 + 1 的清零缓冲区

3) use freadto read the file contents into the buffer

3) 用于fread将文件内容读入缓冲区