【问题标题】:Passing an array of pointer's value to a file in c将指针值数组传递给c中的文件
【发布时间】:2016-03-13 18:02:42
【问题描述】:

我正在使用指针数组将输入的值传递给文本文件,但是当我使用 fputs 时,我不断收到错误“expected 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);    
}
}

【问题讨论】:

  • 在文件中存储指针几乎总是一个非常糟糕的主意。
  • 你创建了一个指向 Book 的指针数组,但你还没有让它们指向任何地方。写a[i]-&gt;isbn 取消引用一个空指针。使用 Book 数组会更简单。

标签: c file pointers


【解决方案1】:

假设你没有给出完整的代码,到目前为止我知道你想将结构元素写入你打开的文件。 在您的 for 循环中,您需要使用 fputs 如下所示,

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

那么它应该可以正常工作而不会出现任何错误。 希望有帮助。

【讨论】:

  • 我刚试过这个,我仍然得到同样的错误。是的,你在写,我确实想将结构元素写入我打开的文件中。
  • @sc100 我通过修改您的代码添加了答案。请看一看。如果它有效,请通过接受帮助他人来验证它。
【解决方案2】:

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

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

希望这会有所帮助。

【讨论】:

  • 你应该解释你做了什么改变以及为什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 2011-04-19
相关资源
最近更新 更多