-
white space and fscanf
Is it possible to get 'fscanf' to read past or ignore whitespace characters???
I need to get a file into an array, but I only get the first few characters up to whitespace. This is what I have so far.
<code>
main()
{
char buffer[200] ;
FILE *infile ;
FILE *outfile ;
infile = fopen( "input.txt", "r" ) ;
outfile= fopen( "output.txt","w" ) ;
fscanf( infile, "%s", buffer ) ;
fprintf( outfile, "%s", buffer ) ;
fclose(infile);
fclose(outfile);
}
</code>
As you can see, I have not implemented the array aspect yet, because my 'output.txt' file only gives me characters up to the first whitespace, instead of the complete file.
Thanks
-
Try using fgets(s,n,file) instead of fscanf(). This will read in a maximum n-1 characters into array s or up to a newline. Use a loop to read multiple lines. fgets() returns NULL when end of file (or error) occurs, so you could use that to terminate your loop.
Something like:
Code:
#include <stdio.h>
#define BUFFER_SIZE 200
int main(void)
{
char buffer[BUFFER_SIZE] ;
FILE *infile ;
FILE *outfile ;
infile = fopen( "input.txt", "r" ) ;
outfile= fopen( "output.txt","w" ) ;
while (fgets( buffer, BUFFER_SIZE, infile ) != NULL)
fprintf( outfile, "%s", buffer ) ;
fclose(infile);
fclose(outfile);
return 0
}
Have a look at the programming FAQ page of this site for more info.
Also note that main() should return int.
-
thanks
Thanks, DAvT.
I will give this a try after looking at the FAQ...
Peace