使用scanf从C中读取txt文件

Reading from txt file in C using scanf

我有一个 txt 文件,我想从中读取。我知道我将不得不阅读 20 行(每行包含 3 个数字变量,例如 10 5 6 等等)

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
int x,y,z;
int counter = 0;

FILE *fid;   
fid = fopen(argv[1],"r");

while(counter<20){
    sscanf(fid,"%d%d%d",&x,&y&z);
    //some operations made on x,y,z
    counter=counter+1;
}

fclose(fid) ;
return 0;
}

不幸的是,它不起作用。 我想浏览文件并使用 sscanf(fid,"%d%d%d",&x,&y,&z) 20 次。 也许我应该扫描?如果有人能告诉我如何让它工作,我将不胜感激。

sscanf 采用 const char * 类型的第一个参数。您将第一个参数作为 FILE * 传递。

您可以使用:

  1. fscanf

  1. fgetssscanf

sscanf 应更改为 fscanf

fscanf扫描文件。

sscanf 扫描字符串。

  1. fscanf 函数

fscanf 函数从指定流的当前位置读取数据到参数列表中的条目给定的位置(如果有的话)。参数列表(如果存在)遵循格式字符串。

int fscanf (FILE *:stream, const char *format, …);

2.sscanf函数

sscanf 函数从缓冲区读取数据到参数列表给定的位置。到达缓冲区指向的字符串末尾等同于 fscanf 函数到达文件末尾 (EOF)。如果缓冲区和格式指向的字符串重叠,则行为未定义。

int sscanf(const char *buffer, const char *format, …);

Quote from this website