Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi, I am programing in C and need to read in some data from a file.Specifically

ID: 3609584 • Letter: H

Question

Hi, I am programing in C and need to read in some data from a file.Specifically the book id, author, and book title. The data isstored in the file like this: "book id,, title,, author"

3477,,   Windows Annoyances,,   David A.Karp
1011,,   The Unix Programming Environment,,  Brian Kernighan & Rob Pike
2012,,   Unix Weekend Crash Course,,   ArthurGriffith

I need to read in the book id first up to the double commas ",,"then the author up to the double commas, then the book title. I amnot sure what would be the best to use. I tried usingfscanf(inFile, "%d", bookData[i].bookID); where inFile is the fileI am getting the data from, and bookData is the struct that I wantto store each book ID into. I am not sure how to then get theauthor and book titles. They have spaces in them so the fscanf willnot work. How can I read in the title up to the ",," and then theauthor?


Thanks

Explanation / Answer

//Here is the c program that will find the data andstore in the structure,
//Don't forget to rate it..


#include<stdio.h>
#include<stdlib.h>
struct data{
char id[1000],author[1000],title[1000];
       }book[1000];
int main(){
    char *ptr;
    int i,j,count=0;
    FILE *fp;
    char str[100],line[1000],temp[1000];
    printf("Enter the file name:");
    scanf("%s",str);
    fp = fopen(str,"r");
    if(fp == NULL)
    {
    printf("can't open file ");
    system("pause");
    }
    while(fgets(line,sizeof(line),fp)!= NULL)
    {
    strcpy(temp,line);
    ptr = (char*)strtok(temp,",,");
    if(ptr != NULL)
    {
    strcpy(book[count].id , ptr);
    ptr = (char*)strtok(NULL,",,");
        if(ptr != NULL)
        {
       strcpy(book[count].author , ptr);
           ptr = (char*)strtok(NULL,",,");
               if(ptr != NULL)
               {
               strcpy(book[count].title , ptr);
               count++;
               }
        }
    }
    }
   
   
    for(i=0;i<count;i++)
    {
    printf("%10s %30s %20s ",book[i].id,book[i].author , book[i].title);
    }
     printf(" ");

    system("pause");
}
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote