473,320 Members | 1,922 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Missing Lines With fscanf()

Hello, trying to get back into c and was having issue with reading a
simple text file with an aribtrary # of lines with 3 int's per line,
with the eventual purpose of putting each int into an element of an
array (eventually will be other things, but I'm sticking to int's for
now). I.e.:
0 1 1
1 1 1
2 1 1 etc...

The problem is it'll read and print all but the last line. Is there
something I'm forgetting about an End Of Line or EOF with fscanf? If
it means anything, I'm using gcc on win32 (djgpp) and haven't been
able to compile it under Linux yet (if there's much difference.) Here
is the minimalist version of the code with all the fault protection
and good stuff taken out for brevity:

#include <stdio.h>

int main() {
char buff[BUFSIZ];
FILE *infile;
int nums[10];

infile = fopen("a.dat", "r");
fscanf(infile, "%d %d %d\n", &nums[0],&nums[1], &nums[2]);
while (!feof(infile)) {
/*future home of parsing junk*/
printf("%d %d %d\n", nums[0], nums[1], nums[2]);
fscanf(infile, "%d %d %d\n", &nums[0], &nums[1], &nums[2]);
}
fclose(infile);

return 0;
}

Much appreciation in advance.
Nov 14 '05 #1
4 2985
Psibur wrote:
Hello, trying to get back into c and was having issue with reading a
simple text file with an aribtrary # of lines with 3 int's per line,
with the eventual purpose of putting each int into an element of an
array [...]
The problem is it'll read and print all but the last line. Is there
something I'm forgetting about an End Of Line or EOF with fscanf? If
it means anything, I'm using gcc on win32 (djgpp) and haven't been
able to compile it under Linux yet (if there's much difference.) Here
is the minimalist version of the code with all the fault protection
and good stuff taken out for brevity:

#include <stdio.h>

int main() {
char buff[BUFSIZ];
FILE *infile;
int nums[10];

infile = fopen("a.dat", "r");
fscanf(infile, "%d %d %d\n", &nums[0],&nums[1], &nums[2]);
while (!feof(infile)) {
/*future home of parsing junk*/
printf("%d %d %d\n", nums[0], nums[1], nums[2]);
fscanf(infile, "%d %d %d\n", &nums[0], &nums[1], &nums[2]);
}
fclose(infile);

return 0;
}


The two problems I can see are addressed in Questions 12.17
and 12.2 of the comp.lang.c Frequently Asked Questions (FAQ) list:

http://www.eskimo.com/~scs/C-faq/top.html

(To understand what role 12.2 plays here, I think you'd do better
to study 12.17 first.)

--
Er*********@sun.com

Nov 14 '05 #2
Psibur wrote:

Hello, trying to get back into c and was having issue with reading a
simple text file with an aribtrary # of lines with 3 int's per line,
with the eventual purpose of putting each int into an element of an
array (eventually will be other things, but I'm sticking to int's for
now). I.e.:
0 1 1
1 1 1
2 1 1 etc...

The problem is it'll read and print all but the last line. Is there
something I'm forgetting about an End Of Line or EOF with fscanf? If
it means anything, I'm using gcc on win32 (djgpp) and haven't been
able to compile it under Linux yet (if there's much difference.) Here
is the minimalist version of the code with all the fault protection
and good stuff taken out for brevity:

#include <stdio.h>

int main() {
char buff[BUFSIZ];
FILE *infile;
int nums[10];

infile = fopen("a.dat", "r");
fscanf(infile, "%d %d %d\n", &nums[0],&nums[1], &nums[2]);
while (!feof(infile)) {
/*future home of parsing junk*/
printf("%d %d %d\n", nums[0], nums[1], nums[2]);
fscanf(infile, "%d %d %d\n", &nums[0], &nums[1], &nums[2]);
}
fclose(infile);

return 0;
}


Try (untested):

#include <stdio.h>

int main(void)
{
FILE *infile;
int nums[10];

if (infile = fopen("a.dat", "r")) {
while (3 == fscanf(infile, "%d %d %d\n",
&nums[0], &nums[1], &nums[2])) {
/*future home of parsing junk*/
printf("%d %d %d\n", nums[0], nums[1], nums[2]);
}
fclose(infile);
}
return 0;
}

NEVER fail to test the result of an input operation. USUALLY test
the result of any system call.

--
"The most amazing achievement of the computer software industry
is its continuing cancellation of the steady and staggering
gains made by the computer hardware industry..." - Petroski
Nov 14 '05 #3
On Fri, 4 Jun 2004, Psibur wrote:
Hello, trying to get back into c and was having issue with reading a
simple text file with an aribtrary # of lines with 3 int's per line,
with the eventual purpose of putting each int into an element of an
array (eventually will be other things, but I'm sticking to int's for
now). I.e.:
0 1 1
1 1 1
2 1 1 etc...

The problem is it'll read and print all but the last line. Is there
something I'm forgetting about an End Of Line or EOF with fscanf? If
it means anything, I'm using gcc on win32 (djgpp) and haven't been
able to compile it under Linux yet (if there's much difference.) Here
is the minimalist version of the code with all the fault protection
and good stuff taken out for brevity:

#include <stdio.h>

int main() {
char buff[BUFSIZ];
FILE *infile;
int nums[10];

infile = fopen("a.dat", "r");
fscanf(infile, "%d %d %d\n", &nums[0],&nums[1], &nums[2]);
while (!feof(infile)) {
/*future home of parsing junk*/
printf("%d %d %d\n", nums[0], nums[1], nums[2]);
fscanf(infile, "%d %d %d\n", &nums[0], &nums[1], &nums[2]);
}
fclose(infile);

return 0;
}


The fscanf in the while loop triggers EOF on reading the last line. After
the last fscanf it goes to the top of the loop, the exit condition is met
and you leave the loop before printing the last lines.

I usually use fgets to read a line then parse it. Another option is to get
the result from fscanf and see how many directives were successful, e.g.

result = fscanf(infile, "%d %d %d\n", &num[0], &num[1], &num[2]);

then exit if result != 3. I'd actually use the fscanf in the while
expression rather than having two calls, e.g.

while(fscanf(infile, "%d %d %d\n", &num[0], &num[1], &num[2]) == 3) {
printf("%d %d %d\n", nums[0], nums[1], nums[2]);
}

This will work even if the last line does not contain a newline character.
It will not print out a line that only has 1 or 2 numbers on it. Something
like:

1 0 1
1 2 1
1 3
1 2 0

will quit after the second line is read.

--
Send e-mail to: darrell at cs dot toronto dot edu
Don't send e-mail to vi************@whitehouse.gov
Nov 14 '05 #4
In article <news:Pi******************************@drj.pf>
Darrell Grainger <da*****@NOMORESPAMcs.utoronto.ca.com> writes:
I usually use fgets to read a line then parse it.
(I think this is usually the best approach.)
Another option is to get the result from fscanf and see how many
directives were successful ...
This has some pitfalls, including one you ran into here:
rather than having two calls, e.g.
while(fscanf(infile, "%d %d %d\n", &num[0], &num[1], &num[2]) == 3) {
printf("%d %d %d\n", nums[0], nums[1], nums[2]);
}
This will work even if the last line does not contain a newline character.
True (assuming the implementation supports such lines in the first
place), but this:
It will not print out a line that only has 1 or 2 numbers on it. Something
like:

1 0 1
1 2 1
1 3
1 2 0

will quit after the second line is read.


is not the case.

The problem lies in the scanf engine's interpretation of "white
space", which disagrees with what most programmers believe is the
"most reasonable" interpretation.

The directive sequence "%d %d %d\n" does *not* mean "three
integers separated by blanks and terminated by a newline." The
final "\n", for instance, means "as much blank space as possible,
including any arbitrary number of newlines, and including no newlines."

The blanks separating the "%d"s *also* mean "as much blank space
as possible, including any arbitrary number of newlines, and including
no newlines."

That means that the third input line -- "1 3\n" -- will be treated
as the number 1 (first "%d"), one blank (first " "), the number 3
(second "%d"), one newline (second " ")... and then the fourth input
line's "1" will be read and converted to satisfy the third "%d". The
newline in the scanf directive will then match the blank after the
1, leaving "2 0\n" in the input stream.

One might attempt to fix this by rewriting the call as:

while (fscanf(infile, "%d%d%d\n", ...) ...)

so that there is no " " directive to match the newline after the
two integers on the third input line ("1 3\n"). But this is no
help, because %d directives include an implied whitespace directive
first. "%d%d%d\n" means exactly the same thing to scanf as
"%d %d %d\n", or even " %d%d \v %d \t\f\r\n"! *All* whitespace
in format directives is equivalent, and any whitespace is equivalent
to an arbitrarily long string of whitespace. Most scanf directives
-- the exceptions are %c and %[ -- have an "implied blank" in front
of them. A final "\n" in a scanf directive means the same thing as
a trailing blank, or "\t", or "\f".

What this all boils down to is that *only* the %c and %[ directives
give you control over "lines". *All* other scanf conversions will
behave poorly in any kind of file-parsing or interactive application.
In other words, these are the only *useful* directives -- unless
you first read in a line, then use sscanf() to pick it apart. (By
using sscanf(), you avoid the problem, because you have a tightly
controlled string in memory, rather than an uncontrolled input
stream coming from a file or user-at-keyboard or whatnot.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: AMT2K5 | last post by:
Hello. I have a file (for a school assignment) with the following format and delimiter format. Each record in the file has the following format: 123423454567987,29873,James,Ha­rry,St....
2
by: CJ | last post by:
Newbie here. Trying to tackle following: Read text file containing list of files delimited by end of line chars. I need to somehow write a loop that filters out each of the lines of text...
7
by: Thomas Sourmail | last post by:
Hi, I hope I am missing something simple, but.. here is my problem: I need my program to check the last column of a file, as in : a b c d target ref 0 0 0 0 1 a 1 0 0 0 1.5 b 2 0 0 0 2 c
7
by: bhanuprakash | last post by:
I am trying to use fscanf to read my test file. In my test file i sometimes have blank lines. When I try to read using the following format. fscanf(fp,"%\n",temp_str); If there is any blank...
9
by: Justme | last post by:
Novice programmer needs help with using fgets to read and ignore the first two lines of a file. I've gone thru the previous posting regarding fgets, but none of them seems to help my situation. I...
9
by: quyvle | last post by:
I can't seem to get this function to work correctly. I'm wondering if anyone could help me out with this. So I'm using the fscanf function to read the input stream and store each string in the...
13
by: PeterOut | last post by:
I am using MS Visual C++ 6.0 on Windows XP 5.1 (SP2). I am not sure if this is a C, C++ or MS issue but fscanf has been randomly hanging on me. I make the call hundreds, if not thousands, of...
6
by: tolkien | last post by:
Hi,i have this problem.I'm reading strings from a text file and i want to know in which line of the file i am. What i did is this: char string; while(!feof(text_file)){...
42
by: Bill Cunningham | last post by:
I'm doing something wrong and all I know to do is turn to clc. I have a text file containing 2 doubles separated by a tab. ..26 0 Is the text. I want to read the two double and printf them...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.