将指针值的数组传递给c中的文件

时间:2016-03-13 18:02:42

标签: c file pointers

我使用指针数组将输入的值传递给文本文件但是当我使用fput时,我不断收到错误"期望const char *",并作为数组指针是从名为books的结构中定义的,它是类型" struct books *"。我尝试使用puts语句,但这也没有解决问题。不使用指针会更好吗?

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);    
}
}

2 个答案:

答案 0 :(得分:1)

假设您没有提供完整的代码,到目前为止我理解您想要将结构元素写入您打开的FILE。 在for循环中,您需要使用fputs以下内容,

fputs(a[i].title, fp);
fputs(a[i].author, fp);
fputs(a[i].status, fp);

然后它应该解决任何错误。 希望有所帮助。

答案 1 :(得分:0)

您好我已修改您的程序如下, 请看看,

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;
}

希望这有助于。