1)
FILE *in = fopen(argv[1], "r");
while(feof(in) == false)
{
int number;
fscanf(in, "%d", &number);
printf("NUMBER: %d\n", number);
}
fclose(in);
2)
char character;
fscanf(in, "%c", &character);
printf("CHAR: %c\n", character);
What if fopen() fails?
> while(feof(in) == false)
feof() isn't what you want to use here. fscanf tells you how many
input items it successfully read; use that to determine when you've
run out of input. See question 12.2 (and probably all of section 12)
of the comp.lang.c FAQ, <http://www.c-faq.com/>.
> {
> int number;
> fscanf(in, "%d", &number);
> printf("NUMBER: %d\n", number);
> }
> fclose(in);
>
> 2)
> char character;
> fscanf(in, "%c", &character);
> printf("CHAR: %c\n", character);
It's hard to tell from your description just what the problem is.
Remember that the new-line that terminates a line is read as a single
character.
Note that getc() or fgetc() is equivalent to fscanf with a "%c"
option.
--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
See what Keith says about checking whether the file opened properly.
> while(feof(in) == false)
> {
> int number;
> fscanf(in, "%d", &number);
> printf("NUMBER: %d\n", number);
> }
> fclose(in);
and the FAQ on use / non-use of feof.
I would tend to use fgets (? fgets correct? I've been using C++ for the
past many years) to read each line into a (null terminated) string
(reads up to the next \n, but replaces the \n with \0) and then use
sscanf to read out of the string. Make sure to declare the char[] long
enough.
At least that will allow for easier debugging.
Best regards,
Jon C.
--
Jonathan Campbell www.jgcampbell.com BT48, UK.
I maybe completely wrong, but what about while ( in >> number) ?
That's C++, the OP doesn't mention it, but his code seems to be C.
Otherwise, this while loop would be correct.
Uli