PDA

View Full Version : File I/O



Unregistered
11-28-2001, 08:31 AM
How can I read several data from a file, which includes one data for each line, and some comments follow those data?
Fox example:
"input.txt"

12.3 ;first data use for ....
34.5 ;second data use for...
90.67 ;3rd data use for...
12098 ;4th data use for...
  

Salem
11-28-2001, 12:31 PM
Like so


#include <stdio.h>
#include <string.h>

int main ( ) {
FILE *fp = fopen( "input.txt", "r" );
char buff[BUFSIZ];
while ( fgets(buff,BUFSIZ,fp) != NULL ) {
float var;
char *comment = strchr( buff, ';' );
if ( comment != NULL ) *comment = '\0'; // blow away the comment
if ( sscanf( buff, "%f", &var ) == 1 ) {
printf( "Data=%f\n", var );
} else {
printf( "Garbage in %s", buff );
}
}
return 0;
}