【问题标题】:Reading from txt file in C using scanf使用scanf从C中的txt文件读取
【发布时间】:2015-03-14 10:59:17
【问题描述】:

我有一个 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",&amp;x,&amp;y,&amp;z) 20 次。 也许我应该scanf?如果有人能告诉我如何使它工作,我将不胜感激。

【问题讨论】:

标签: c file scanf


【解决方案1】:

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

你可以使用:

  1. fscanf

  1. fgetssscanf

【讨论】:

    【解决方案2】:

    sscanf 应更改为 fscanf

    fscanf扫描文件。

    sscanf 扫描字符串。

    1. fscanf 函数

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

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

    2.sscanf函数

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

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

    Quote from this website

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多