简体   繁体   English

使用 fread 快速阅读而不使用 fwrite

[英]fast reading with fread without using fwrite

I have a graph in the following format:我有以下格式的图表:

3 15 12
15 15
12 35
12 54

where the first line is some info about the graph and the first letter on the first line is the number of edges.其中第一行是关于图形的一些信息,第一行的第一个字母是边数。 The following m lines are the edges.以下 m 行是边。 I can easily read this file with scanf.我可以使用 scanf 轻松读取此文件。 But now I am looking to understand fread to read all the edges at once and not each line one at a time.但现在我希望了解 fread 一次读取所有边缘,而不是一次读取每一行。

int main () {
int32_t row1[3];

printf("row1[0]=%d, row1[1]=%d, row1[2]=%d\n", row1[0], row1[1], row1[2]);
FILE* in;
in = fopen("in", "r");
fread(&row1, sizeof(int32_t), 3, in);

fclose(in);
printf("row1[0]=%d, row1[1]=%d, row1[2]=%d\n", row1[0], row1[1], row1[2]);
}

But I do not get the output 3, 15, 12 as I expect from the last printf.但我没有得到 output 3、15、12,正如我对最后一个 printf 所期望的那样。

Do you need to create the in file with fwrite or can you create it in any way?您需要使用 fwrite 创建 in 文件还是可以以任何方式创建它?

It's possible to read the whole file at once.可以一次读取整个文件。 It can be done like this.可以这样做。 I omitted error checking for malloc and fread.我省略了 malloc 和 fread 的错误检查。

fseek(in, 0L, SEEK_END);
size_t size = ftell(in);
rewind(in);
char buffer = malloc(size);
fread(buffer, size, 1, in);

But then you need to parse the buffer.但是你需要解析缓冲区。 There's not much to gain from this.从中没有什么好处。 If you want to read a text file, then fgets is usually the way to go.如果要读取文本文件,则fgets通常是 go 的方式。 Reading line by line with fread makes little sense.fread逐行阅读没有什么意义。 The function is intended for binary files. function 适用于二进制文件。 You would have to manually search for line breaks.您将不得不手动搜索换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM