使用 fscanf 逐行读取 [英] Reading line by line using fscanf

查看:141
本文介绍了使用 fscanf 逐行读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个包含 3 行的文件:

I want to read a file with 3 lines:

第一个是字符串,第二个是数字,第三个是字符串.

The first one with strings, second with a number and the third with strings again.

示例:

Line 1:鸟玩具书电脑水

Line 1: bird toy book computer water

第 2 行:2

第 3 行:玩具水

我有这段代码,它读取一个文件,逐字将它们存储在单词数组中,然后将单词放入单词 2d 数组中.

I have this code, that reads a file, word by word storing them in the word array, and then putting the word into the words 2d array.

char words [5][50];
char word [50];
int i,j;
j = 0;

while( (fscanf(file, "%s", word))!=EOF ){
    for(i = 0; i<50; i++){
        if(word[i] != NULL){
            words[j][i] = word[i];
        } else{
            break;
        }
    }
    j++;

}

它正在工作,但它读取所有行,我想要一种方法来为第一行执行此过程,然后将第二行存储到 int 变量中,将第三行存储到另一个二维数组中.

it's working, but it reads all the lines, i want a way to just do this process for the first line, and then store the second line into a int variable and the third line into another 2d array.

推荐答案

阅读更多关于 fscanf.不适合逐行阅读.

Read more about fscanf. It is not suitable to read line by line.

考虑使用 fgets 甚至更好(在 POSIX) 与 getline(参见 this),然后解析每一行也许与 sscanf.它的返回值(从 sscanf 等给出的扫描项目的计数)可能对测试很有用(并且您可能还想在扫描控件中使用 %n格式字符串;正如 Jonathan Leffler 评论的那样,另请阅读关于 %ms 分配分配修饰符,至少在 POSIX 系统上,请参阅 Linux sscanf(3)).

Consider instead reading every line with fgets or even better (on POSIX) with getline (see this), then parse each line perhaps with sscanf. Its return value (the count of scanned items given from sscanf etc...) could be useful to test (and you might also want to use %n in the scan control format string; as Jonathan Leffler commented, read also about %ms assignment-allocation modifier, at least on POSIX systems, see Linux sscanf(3)).

顺便说一句,像 50 这样的硬编码限制是不好的口味(而不是 健壮).或许可以考虑更系统地使用 C 动态内存分配(使用 mallocfree 和朋友)和指针,有时可能使用 <在您的某些 struct-s

BTW, hard-coding limits like 50 for your word length is bad taste (and not robust). Consider perhaps using more systematically C dynamic memory allocation (using malloc, free and friends) and pointers, perhaps using sometimes flexible array members in some of your struct-s

这篇关于使用 fscanf 逐行读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆