0

I want to read this

                zeyad,aar,eee,100,sss,55,science
                toto,art,bb,100,ss,55,drawing

from a file then store it in a structure of books.title,books.publisher etc,, as shown below

Can Somebody tell me how to not read the commas and just store string in its place? what I tried is using %*C between each string but it does not work.

while (!feof(pBook))
{
    fscanf(pBook,"%s%*c%s%*c%s%*c%s%*c%s%*c%d%*c%s",
        books[z].Title,books[z].Author,books[z].Publisher,books[z].ISBN,books[z].DOP,
        &books[z].Copies,books[z].Category);
    fscanf(pBook,"\n");
    z++;
}
fclose(pBook);
Zeyad Ibrahim
  • 13
  • 1
  • 7

2 Answers2

1

A simple example (not tested):

void SeparateCommas(char *FileName)
{
 FILE *fd = fopen(FileName, "r");
 size_t len = 0;
 ssize_t read;
 char *line = NULL;
 char temp[50][32];
 char *token;
 char *end_str;

 while((read = getline(&line, &len, fd)) != -1)
    {
     printf("Read line: %s", line);
     token = strtok_r(line, ",", &end_str);

     while(token != NULL)
         {
          strncpy(temp[i], token, sizeof(temp[i]));
          printf("Read word: %s", temp[i]);
          token = strtok_r(NULL, ",", &end_str);
          i++;
         }
    }       
}
Fabio_MO
  • 713
  • 1
  • 13
  • 26
  • 1
    With `strncpy(temp[i], token, sizeof(temp[i])); printf("Read word: %s", temp[i]);` Why use a string copy with limitations, yet then potentially print an array without a null character? – chux - Reinstate Monica Dec 01 '17 at 16:40
0

Can Somebody tell me how to not read the commas and just store string in its place?

Since %s matches a sequence of non-white-space characters, it cannot be used to not read the commas. For your purposes %[…], which matches a nonempty sequence of characters from a set of expected characters (the scanset), can be used, whereby the character after the left bracket is a circumflex (^), in which case the scanset contains all characters that do not appear between the circumflex and the right bracket:

    while (fscanf(pBook, "%[^,],%[^,],%[^,],%[^,],%[^,],%d,%s\n",
            books[z].Title, books[z].Author, books[z].Publisher, books[z].ISBN,
            books[z].DOP, &books[z].Copies, books[z].Category) == 7) ++z;

I assume you ensured that all strings in the input file fit into the size reserved for their respective structure element, otherwise you would have used a maximum field width.

Armali
  • 18,255
  • 14
  • 57
  • 171