我正在尝试编写一个 C 函数,该函数从文件中读取第一行文本,然后使用fseek()和ftell()来获取文件其余部分的大小(文件减去第一行)。
我的想法是用一秒钟的时间FILE *fp1来获取原始文件的位置FILE *fp,并用 发送fp1到文件的末尾fseek(),这样我就不必移动原始文件fp并失去其位置。
这是我的代码。编译器告诉我不能分配fp1给fp,因为fp1is aFILE*和fpis a struct FILE*。
我可以通过这种方式实现我想要做的事情吗?
FILE *fp, fp1;
fp = fopen(filename, "r");
if (!fp)
return 0;
fscanf(fp, "%1d", m); //Lines 15-18 read the first line of the file
fscanf(fp, "%*1c");
fscanf(fp, "%1d", n);
fscanf(fp, "%*1c");
fp1 = fp; //<---------- This is my problem.
//how do I set fp1 to the same place in the
//file as fp?
fseek(fp1, 0, SEEK_END);
*file_size = ftell(fp1);
Run Code Online (Sandbox Code Playgroud)
这只是将指针复制到文件句柄。正确的方法是在移动之前保存 ftell 结果,并在移动到文件末尾后再次移回。
所以:
long saved = ftell(fp);
fseek(fp, 0, SEEK_END);
*file_size = ftell(fp);
fseek(fp, saved, SEEK_SET);
Run Code Online (Sandbox Code Playgroud)