Home > Enterprise >  How to read the data store in .txt file which are sparated by comma?
How to read the data store in .txt file which are sparated by comma?

Time:12-01

I need to read the data store in .txt file which are sparated by comma. StudentList.txt

Olivia,SWANSON,F,29001,20
Emma,ONEILL,F,7900,19

According to online assitance, I tried the following operations:

FILE *fp;
char fname[20];
char sname[20];
char gender[2];
int ID;
int age;
fp = fopen("C:\\Users\\Catlover\\Desktop\\DSA\\Program2\\StudentList.txt", "r");
if(fp == NULL){
    perror("Open fail.");
    exit(1);
    }
while(fscanf(fp, "%s,%s,%s,%d,%d", fname, sname, gender, &ID, &age) == 5)
{
    printf("%s, %s, %s, %d, %d", fname, sname, gender, ID, age);
}
fclose(fp);
return 0;

May be I have some wrong understandings about the principle of function fscanf

There is nothing output.

CodePudding user response:

Read the line of data into a string with fgets() and then parse. Use " %n" to detect success. "%n" records the offset of the scan, if it got that far. Use [^,], to read up to 19 non-commas and then a comma.

// while(fscanf(fp, "%s,%s,%s,%d,%d", fname, sname, gender, &ID, &age) == 5) {
//   printf("%s,%s,%s,%d,%d\n", fname, sname, gender, ID, age);
// }

#define LINE_SIZE 100
char buf[LINE_SIZE];

while(fgets(buf, sizeof buf, fp)) {
  // Now parse it
  int n = 0;
  sscanf(buf, "[^,],[^,],%1[^,],%d,%d %n", 
    fname, sname, gender, &ID, &age, &n);
  if (n > 0 && buf[n] == 0) {
    // Success
    printf("%s,%s,%s,%d,%d\n", fname, sname, gender, ID, age);
  } else {
    printf("Trouble with <%s>\n", buf);
  } 
}

CodePudding user response:

First mistake: You are not checking, whether the file has been opened successfully. fp will be 'NULL' if opening failed and any follow up operation will fail if it does.

Second: %s consumes every character until the first whitespace character it finds, including the comma. Try [^,], instead. (Which will stop once it finds a comma).

  • Related