用C语言读取文件 [英] Reading a file in C language

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

问题描述



我有一个文件,其内容如下:
S#名称从要训练的#DOJ Fiar
1 Srikumar COCHIN KOLKATTA 12515 2012/12/12 530

现在,我只需要获取From,To和DOJ列.

我已经尝试过了,

fscanf(fp,%s,%s,%s",frm,to,doj);

但它显示的是前三列.

而且我需要将日期存储在数组中.

请帮忙.

Hi,

I have a file which has the contents as follows :
S# Name From To Train# DOJ Fiar
1 Srikumar COCHIN KOLKATTA 12515 12/12/2012 530

Now, I need to get only the columns From, To and DOJ.

I have tried,

fscanf(fp,"%s,%s,%s",frm,to,doj);

But it is showing the first 3 columns.

And I need to store the date in to an array.

Please help.

推荐答案

fscanf按设计工作.它需要前三个字符串.

我有两个选择:
1)
添加假人"之类的
fscanf works as designed. It takes the first three strings.

I have two options:
1)
Add "dummys" like
fscanf("%s %s %s %s %s %s", dummy1, dummy2, from, to, dummy3, doj);



始终要注意目标字符串的缓冲区大小!

2)
使用fgets()读取整行,并使用srtok分隔字符串

您可以在这里找到更多关于行程的信息 http://www.cplusplus.com/reference/clibrary/cstring/strtok/ [ ^ ]



Allways pay attention on the buffer size of your target strings!

2)
Read the whole line with fgets() and seperate the string with srtok

You can find more on strok here e.g. http://www.cplusplus.com/reference/clibrary/cstring/strtok/[^]


您可以使用*规范跳过您不感兴趣的字段.还应该使用width规范来限制任何字段读取的字符数,以防止缓冲区溢出.像这样的东西:
You can use the * specification to skip fields that you are not interested in. You should also use the width specification to limit the number of characters read for any field, to guard against buffer overrun. Something like:
char szFrom[32];
char szTo[32];
char szDOJ[12];
int nFieldCount = fscanf(fpInput, "%*s %*s %32s %32s %*s %12s %*s", szFrom, szTo, szDOJ);


我不确定您的意思是我需要将日期存储到数组中." .


I''m not sure what you mean by "I need to store the date in to an array.".


您不能简单地丢弃您不输入的信息不需要吗?
例如
Cannot you simply discard the info you don''t need?
e.g.
int s; // will be discarded
// use 'large-enough' buffers.
char n[0x20]; // will be discarded
char f[0x20];
char t[0x20];
int d;


if ( fscanf(fp, "%d %s %s %s %d", &s, n, f, t,&d) != 5)
{
  // handle error
}

printf("from %s to %s doj %d\n", f, t, d);


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

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