I have a CSV file tab-delimited that I am trying to read through C. fields are separated by tab but there are few null fields as well.. I am using fscanf(fileptr,"[^\t]s",field); to read a single field, the issue I am getting it did not help me to identify those fields that are null.. i also tried this fscanf(fileptr,"%s\t%s\t",field1,field2); but I am facing the same issues, even in the second method if I have a field separated with space,I didn't get it proper because %s will only read-string without white spaces. How to achieve that?
int main() {
FILE *fp = fopen( "your_file_here", "r");
if( fp == NULL ){
return 1; //file not exists or locked by another process
}
char mystr[1024]; //buffer for read data from file
while( !feof( fp ) ) { //loop trough file
if( fgets( mystr, 1024, fp ) != NULL ) { //read line
int len = strlen( mystr ); //string length
//trim \n or \r from ending of string
for ( int i = len -1; i >= 0; i-- ) {
if( mystr[ i ] == '\r' || mystr[ i ] == '\n' ){ //if ending has an \r or \n
mystr[ i ] = 0; //set this to \0
}
else{ //else
break; //leave loop
}
}//end trim
//tokenize the mystr by search for \t and store the
//chars in tokenBuff
//if \t found, the tokenBuff is ready for output
//the last token by found NULL is also ready for output
char tokenBuff[1024];
menset( tokenBuff, 0, 1024 );
int offset = 0;
int tokenBuffOff = 0;
while( true ){
if( mystr[ offset ] == '\t' ){
printf( "token: %s\n", tokenBuff );
memset( tokenBuff, 0, 1024 );
tokenBuffOff = 0;
}
else{
if( mystr[ offset ] == '\0' ){
if( tokenBuff != NULL ){
printf( "token: %s\n", tokenBuff );
}
break;
}
else{
tokenBuff[ tokenBuffOff ] = mystr[ offset ];
tokenBuffOff++;
}
}
offset++;
}//end tokenize
}//end if fgets
}/end while
fclose(fp) ;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.