reading data from file in c

故事扮演 提交于 2019-12-06 04:34:05
Bobby Stenly

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..

This looks like a homework problem, so I will try to give you some good advice.

First, read the description of the fscanf function and the description of the "%s" conversion.

Here is a snip from the description I have for "%s":

Matches a sequence of non-white-space characters; the next pointer must be a pointer to a character array that is long enough to hold the input sequence and the terminating null character (’\0’), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

Here are the two important points:

  • Each of your input lines contains numbers and whitespace characters. So the function will read a number, reach whitespace, and stop. It will not read 9 characters.
  • If it did read 9 characters, you do not have enough room in your array to store the 10 bytes required. Note that a "terminating null character" will be added. 9 characters read, plus 1 null, equals 10. This is a common mistake in C programming and it is best to learn now to always account for the terminating null in any C string.

Now, to fix this to read characters into a two dimensional array: You need to use a different function. Look through your list of C stdio functions.

See anything useful sounding?

If you haven't, I will give you a hint: fread. It will read a fixed number of bytes from the input stream. In your case you could tell it to always read 9 bytes.

That would only work if each line is guaranteed to be padded out to 9 characters.

Another function is fgets. Again, carefully read the function documentation. fgets is another function that appends a terminating null. However! In this case, if you tell fgets a size of 9, fgets will only read 8 characters and it will write the terminating null as the 9th character.

But there is even another way! Back to fscanf!

If you look at the other conversion specifiers, you could use "%9c" to read 9 characters. If you use this operation, it will not add a terminating null to the string.

With both fread and fscanf "%9c" if you wanted to use those 9 bytes as a string in other functions such as printf, you would need to make your buffers 10 bytes and after every fread or fscanf function you would need to write save[9] = '\0'.

Always read the documentation carefully. C string functions sometimes do it one way. But not always.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!