Reputation: 27
I'm using an array of pointers to pass the inputted values to a text file but when I use fputs I keep getting the error "expected const char*", and as the array of pointers is defined from the struct named books it is of the type "struct books *". I tried using the puts statement but that doesn't solve the problem either. Would it be better not to use pointers?
const char *BOOKS = "books.txt";
struct Books{
int isbn;
char title[25];
char author[20];
char status[10];
}*a[MAX];
int main (void)
{
int i;
printf("Enter the books details that you currently have:\n\n");
for(i=0;i<MAX;i++)
{
printf("Enter the book's isbn number:");
scanf("%d", &a[i]->isbn);
printf("Enter the book's title :");
scanf("%s", &a[i]->title);
printf("Enter the book's author:");
scanf("%s", &a[i]->author);
printf("Enter the book's status, whether you 'have' or whether it is 'borrowed':");
scanf("%s", &a[i]->status);
}
FILE *fp = fopen(BOOKS, "r+" );
if (fp == NULL )
{
perror ("Error opening the file");
}
else
{
while(i<MAX )
{
fputs( a[i]->status, fp);
fputs(a[i]->author, fp);
fputs( a[i]->title, fp);
fputs( a[i]->isbn, fp);
}
fclose (fp);
}
}
Upvotes: 0
Views: 241
Reputation: 1147
Hi I have modified your program as follow, Please have a look,
const char *BOOKS = "books.txt";
struct Books{
int isbn;
char title[25];
char author[20];
char status[10];
}a[MAX];
int main (void)
{
int i;
char *ISBN;
printf("Enter the books details that you currently have:\n\n");
for(i=0;i<MAX;i++)
{
printf("Enter the book's isbn number:");
scanf("%d", &a[i].isbn);
printf("Enter the book's title :");
scanf("%s", &a[i].title);
printf("Enter the book's author:");
scanf("%s", &a[i].author);
printf("Enter the book's status, whether you 'have' or whether it is 'borrowed':");
scanf("%s", &a[i].status);
}
i = 0;
FILE *fp = fopen(BOOKS, "r+" );
if (fp == NULL )
{
perror ("Error opening the file");
}
else
{
while(i<MAX )
{
fputs( a[i].status, fp);
fputs(a[i].author, fp);
fputs( a[i].title, fp);
itoa(a[i].isbn,ISBN,10); // Convert the isbn no to const char* in decimal format. to write in to the file.
fputs( ISBN, fp);
i++; //Increment 'i' to access all the elements
}
fclose (fp);
}
return 0;
}
Hope this Helps.
Upvotes: 0
Reputation: 1147
Assuming you have not given the complete code, So far I understand you want to write the structure elements to the FILE you have opened.
In your for
loop you need to use fputs
some thing as follow,
fputs(a[i].title, fp);
fputs(a[i].author, fp);
fputs(a[i].status, fp);
Then it should work with out any error. Hope That Helps.
Upvotes: 1