Home > Mobile >  how can I use strtok to use each line as an element?
how can I use strtok to use each line as an element?

Time:06-26

I have a .txt/.csv file that stores names along with their password as shown below:-

google, ,9* =<=2=

google, ;5290= :

Each induvial line is a separate entity. I was trying to make an array with induvial entities as its elements. I was trying to use strtok with \n as delimiter. But it throws me the following error.

test.c:11:21: error: invalid initializer

char line[100]= strtok(buffer,"\n") ;

               ^~~~~~

Where am I going wrong? Here is the full block of the particular code:-

FILE* fp;
    fp=fopen("storeroom.csv","r");
    char buffer[100];
    rewind(fp);
    fread(buffer, sizeof(buffer), 1, fp);
    fclose(fp);
    char line[100]= strtok(buffer,"\n") ;
    printf("%s",line);

CodePudding user response:

You may initialize an array with a braced list. So this declaration

char line[100]= strtok(buffer,"\n") ;

is incorrect. Moreover the element type of the array is char while the initializer expression has the type char *.

You could write for example

char *line = strtok(buffer,"\n") ;
puts( line );

Here is a demonstration program.

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

int main( void )
{
    char s[] = "Hello\nWOrld!";
    char *p = strtok( s, "\n" );

    puts( p );
}

The program output is

Hello

CodePudding user response:

Try fgets to read each line.
This will read each line. The newline will be included for lines less than 99 characters. strcspn can be used to remove the newline.

FILE* fp;
fp=fopen("storeroom.csv","r");
char buffer[100];
while ( fgets ( buffer, sizeof buffer, fp)) {
    buffer[strcspn ( buffer, "\n")] = 0; // remove newline
    printf("%s\n",buffer);
}
fclose(fp);
  •  Tags:  
  • c
  • Related