Connecting Tech Pros Worldwide Forums | Help | Site Map

Stupid C Question: fscanf to read a whole line from file

Newbie
 
Join Date: May 2006
Posts: 1
#1: May 13 '06
Howdy,
(I'm a newbie C programmer, by the way...) How would one go about reading a whole line from file?
I was told that something like:
fscanf("%s\n", string);
but it wasn't working for me.... I just need to read in a whole line from a file into a char array.
Help!!

Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,188
#2: May 13 '06

re: Stupid C Question: fscanf to read a whole line from file


Well to start with you are using fscanf incorrectly the prototype for fscanf is #

int fscanf( FILE *stream, const char *format [, argument ]... );

You have not put in the stream parameter. If you include the correct header files (stdio.h in this case), which you should always do then you would certainly have got a warning from your compiler if not an error.

Additionally even if you fixed that you are running a risk using fscanf like that because if the file contains a line longer than the sizeof(string) you will overwrite the end of the array and invoke undefined behaviour (which means anything could happen including you computer growing legging and going off to setup a hippie commune).

I suggest that you use fgets, prototype

char *fgets( char *string, int n, FILE *stream );

This function reads a line from a file but this the provisor that it doesn't read more than n bytes protecting against the case of overwriting the end of string.
Reply