【问题标题】:confusion with fseek() in C与 C 中的 fseek() 混淆
【发布时间】:2021-04-07 23:46:04
【问题描述】:

我是 C 编程语言的新手。我正在学习文件 I/O,并且对 fseek 函数感到困惑。这是我的代码

#include <stdio.h>
#include <stdlib.h>
struct threeNumbers {
int n1,n2,n3;
}
int main (){
int n;
struct threeNumbers number;
FILE *filePointer;
if ((filePointer=fopen("\\\\wsl$\\Ubuntu-20.04\\home\\haseeb\\learningC\\file Input and Output\\program2\\program.bin","rb"))==NULL){
printf("error! opening file);
/* if pointer is null, the program will exit */
exit(1);
}
/* moves the cursore at the end of the file*/
fseek(filePointer,-sizeof(struct threeNumbers),SEEK_END);
for(n=1;n<5;++n){
fread(&number,sizeof(struct threeNumbers),1,filePointer);
printf (" n1:%i\tn2:%i\tn3:",number.n1,number.n2,number.n3);
fseek(filePointer,-2*sizeof(struct threeNumbers),SEEK_CUR);
}
fclose(filePointer);
return 0;
}

我知道这个程序将开始以相反的顺序(从后到前)从文件 program.bin 中读取记录并打印出来。 我的困惑是我知道“fseek(filePointer,-sizeof(struct threeNumbers),SEEK_END);”将光标移动到二进制文件的末尾。 “fseek(filePointer,-2*sizeof(struct threeNumbers),SEEK_CUR);”是什么意思做?我认为它会移动到当前位置,但是在这个程序中光标指向当前位置的意义何在?还有为什么它是 -2 而不是“-sizeof(struct threeNumbers)”?

【问题讨论】:

  • printf("error! opening file); 中缺少 " 这就是为什么代码中的语法高亮不起作用的原因。
  • FILE *filePointer = fopen( ... ); 然后if ( filePointer == NULL ) ... 比将作业塞进if 语句更容易阅读和纠正。将赋值塞入if 语句是一个坏主意,会导致代码难以阅读且容易出错。教你这样做的人从来没有接受过 24 小时电话修复生产代码中的错误。
  • 除了缺少结束引号,printf("error! opening file"); 还有其他问题。这是无用错误消息的典型示例,它被写入错误的位置。将错误消息写入 stderr,包括用于打开文件的路径,并包括错误原因。 FILE *fp = fopen(path, mode); if( fp == NULL ) { perror(path); ...
  • 将文件按反向索引顺序读取到struct数组中会更容易:for(n=4; n&gt;=0; n--),然后打印结果,无需查找。
  • 它向后移动-2结构的原因是因为在读取了一个struct之后文件指针在下一个位置,因此您需要向后移动2个结构在前一个。如果您只移回 1 个结构,您将继续阅读相同的结构。

标签: c


【解决方案1】:

忽略实际代码,fseek() 是这样做的:

       The  fseek()  function  sets the file position indicator for the stream
       pointed to by stream.  The new position, measured in bytes, is obtained
       by  adding offset bytes to the position specified by whence.  If whence
       is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset  is  relative  to
       the  start of the file, the current position indicator, or end-of-file,
       respectively.  A successful call to the  fseek()  function  clears  the
       end-of-file  indicator  for  the  stream  and undoes any effects of the
       ungetc(3) function on the same stream.

fseek(filePointer,-sizeof(struct threeNumbers),SEEK_END)“将光标移动到二进制文件的末尾”;它会将sizeof(struct threeNumbers) 移动到文件末尾之前。

【讨论】:

  • 同样适用于SEEK_CUR,它不像OP认为的那样moves to the current location
猜你喜欢
  • 2014-11-18
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 2012-05-20
  • 2017-07-22
  • 2014-08-05
  • 2022-01-19
  • 1970-01-01
相关资源
最近更新 更多