从C文件中读取数据 [英] reading data from file in c

查看:338
本文介绍了从C文件中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为概率txt文件,其中包含:

  6 2 8 3
4 98652
      914
143 789
    1
527 146
 85
 1 74 8
7 6 3

每个行有9个字符,有9条线。因为我不能让在C字符串数组,即时通讯使用一个二维数组。小心运行code,无限循环是常见的,它打印输出怪异。林也好奇的是,它在哪里停止服用字符串中?直到换行?
为每一个拯救预期的结果:6 2 8 3
或watever线体。

 的#include<&stdio.h中GT;
FILE *概率;主要()
{
    概率= FOPEN(prob.txt,R);    炭grid_values​​ [9] [9];
    焦炭保存[9];    INT I;
    对于(i = 0;(的fscanf(概率,%S,保存)= EOF);!我++)
    {
        INT N;
        为(N = 0; N< = 9; N ++)
        {
            grid_values​​ [I] [N] =保存[N];
            的printf(%C,grid_values​​ [I] [N]);
        }
    }
    FCLOSE(概率);
}


解决方案

如果您使用的fscanf ,将空间分隔符后停止。

尝试与fgets 来做到这一点。它会读取一行行..

 为(i = 0;!(与fgets(保存的sizeof(保存),概率)= EOF);我++)

与fgets 的使用可以在这里找到细节:结果
http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

- 编辑 -

这里的第二个

 而(!的feof(文件))
{
    与fgets(S,sizeof的(多个),文件); ......
}

我认为它会工作得很好。

I have a txt file named prob which contains:

  6 2 8 3
4   98652
      914
143   789
    1    
527   146
 85      
 1 74   8
7   6 3  

Each line has 9 chars and there are 9 lines. Since I cant make a string array in c, im be using a two dimensional array. Careful running the code, infinite loops are common and it prints weird output. Im also curious as to where does it stop taking in the string? until newline? expected result for each "save": 6 2 8 3 or watever the line contained.

#include <stdio.h>
FILE *prob;

main()
{ 
    prob = fopen("prob.txt", "r");

    char grid_values[9][9];
    char save[9];

    int i;
    for (i = 0; (fscanf(prob, "%s", save) != EOF); i++)
    {
        int n;
        for (n = 0; n <= 9; n++)
        {
            grid_values[i][n] = save[n];
            printf("%c", grid_values[i][n]);
        }
    }
    fclose(prob);
}

if you use fscanf, it will stop after a space delimiter..

try fgets to do it.. It will read line by line..

for (i = 0; (fgets(save, sizeof(save), prob) != EOF); i++)

the detail of fgets usage can be found here:
http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

--edited--

here's the second

while(!feof(file))
{
    fgets(s, sizeof(s), file); ......
}

I think it'll work well..

这篇关于从C文件中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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