-
Scan data from file
Now I would like to open one data file, which utilizes the ';' to start commend. I want to scan all data before ;, which use a blank to separate each other.
The following code I just can scan the first data, how can I modify it to scan the following data before ';'.
Thanx a lot.
#include <stdio.h>
#include <string.h>
int main ( )
{
FILE *fp = fopen( "input.txt", "r" );
char buff[BUFSIZ],c;
int i;
float data[100];
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 );
}
system("PAUSE");
return 0;
}
-
like this
PHP Code:
#include <stdio.h>
int main()
{
FILE*fp=fopen("input.txt","r+");
float data[100];
char test;
int i;
while(!feof(fp)&&test=getc(fp)!=';')
{
ungetc(test,fp);
fscanf(fp,"%f",&data[i]);
i++;
}
}
-
You shouldn't loop in this manner:
Code:
while(!feof(fp)&&test=getc(fp)!=';')
{
ungetc(test,fp);
fscanf(fp,"%f",&data[i]);
i++;
}
Using feof() in the way isn't guaranteed to produce the desired results. You should check the return code from getc() against EOF to see if you're at the end of a file. To do this, make use the variable you are assigning the return value to is an int.
Code:
int c;
while ((c = getc(fp)) != EOF)
{
/* do stuff */
}
Also, better check the return code from fscanf() to ensure it did actually read a float into the output variable.
The int i needs initialising before you use it too, it's starting value undefined.