阅读人数从在C文件 [英] Read in Numbers from a File in C

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

问题描述

我有一个名为 points.dat 文件其内容是这样的:结果
5结果
2 5结果
-1 18结果
0 6结果
1 -1结果
10 0

I have a file called points.dat which reads something like:
5
2 5
-1 18
0 6
1 -1
10 0

第一个号码是多少下令对有。接下来的5条线路包含这些有序对。我能做些什么在第一个数字阅读,确定有多少个有(从这里我能的malloc 阵列结构来点存储)。

The first number is how many ordered pairs there are. The next 5 lines contain those ordered pairs. What can I do to read in the first number, determine how many points there are (from here I can malloc an array of structs to store the points in).

我的问题是,龟etc 并没有真正做的工作在这里。如果第一个数字是什么两位数?说的第一个号码是10. 龟etc 将只检索'1'。此外,与fgets 并没有真正的工作,因为你需要提供你想要在阅读文字量的长度。这同样适用于的fscanf

My problem is that fgetc doesn't really do the job here. What if the first number is two digits? Say the first number is 10. fgetc will only retrieve the '1'. Also, fgets doesn't really work, since you need to supply it the length of the amount of characters you want to read in. The same applies for fscanf.

真正的麻烦进来时,它的时间来检索有序对。我不知道如何可以做到这一点。我唯一​​的想法到目前为止是看行:如果它看到非空格或非 - 的'\\ n的,它将为x数读点1环的坐标。获取y坐标。一旦它击中的'\\ n',它现在将移动到下一行,并开始寻找价值在未来结构 <$ C数组中存储$ C>结构。

The real trouble comes in when it's time to retrieve the ordered pairs. I have no idea how to do this either. My only thoughts so far is look at a line: if it sees non-spaces or non-'\n's, it will read in the number as the x coordinate of point 1. Loop. Get y coordinate. Once it hits a '\n', it will now move on to the next line, and begin looking for values to store in the next struct in the array of structs.

(虽然这样做,我也需要确保的atoi 可所有这些转换成整数...)。

(While doing this, I also need to be sure atoi can convert all of these into integers... ).

如果任何人有任何想法,以帮助,他们是AP preciated。

If anyone has any ideas to help, they are appreciated.

推荐答案

有关的第一行使用 INT numValues​​Read =的fscanf(文件%d个,&安培; totnums);

然后,使用 numValues​​Read =的fscanf(文件%D,&安培; NUM1,&安培; NUM2); 来读取其他行

Then, use numValuesRead = fscanf(file, "%d %d", &num1, &num2); to read the other lines.

的fscanf 返回读取的值数。您应经常检查它。

fscanf returns the number of value read. You should always check it.

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

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