【问题标题】:Reading a line from a text file into an array of characters in c将文本文件中的一行读入c中的字符数组
【发布时间】:2015-10-11 02:07:57
【问题描述】:

我正在尝试从文本文件中填充数组。该数组位于一个结构中:

struct ISBN
{
    long value;
};
struct Author
{ 
    char authorName[60];
};
struct  Book
{
    char *bookTitle;
    struct Author bookAuthor;
    struct ISBN bookID;
};

我尝试编写一个填充函数,该函数采用 Book 类型的文件和结构,如下所示:

void fillin (FILE * file, struct Book * bk)
{
    bk->bookTitle =(char*) malloc(1000);
    size_t n = 0;
    int c;

    file=fopen("book.txt","r");

    while ((c = fgetc(file)) != '\n')
    {
        bk->bookTitle[n++] = (char) c;
    }

    bk->bookTitle[n] = '\0'; 

    fscanf(file,"%s", &bk->bookAuthor.authorName);
    fscanf(file,"%lld",&bk->bookID.value);

    //fscanf(file,"%s", &bk->bookTitle);
}

文件 book.txt 有这个数据:

UNIX Network Programming
W. Richard Stevens
0131411551

问题是,它不能扫描数组,我想从文本文件中填充 bookTitle 和 autherName 数组。

【问题讨论】:

    标签: c arrays io


    【解决方案1】:

    下面这行是错误的:

    fscanf(file,"%s", &bk->bookAuthor.authorName);
    

    当你扫描一个字符串时,字符数组已经是一个指针,所以你不要取它的地址(&)。试试:

    fscanf(file,"%s", bk->bookAuthor.authorName);
    

    为了安全(如果是长字符串),你可以使用这个函数:

    char * fgets ( char * str, int num, FILE * stream );
    

    因此:

    fgets(bk->bookAuthor.authorName, 60, file);
    

    如果行太长,则不会复制字符串的其余部分。如果这样做,您可能必须检查字符串是否尚未终止,并丢弃其余字符,直到换行符。 (例如while ((c = fgetc(file)) != '\n');)。 \n 字符被复制进来,因此您必须找到并删除它:

    bk->bookAuthor.authorName[59] = 0; // make sure it is null-terminated
    int last = strlen(bk->bookAuthor.authorName)-1;
    if (bk->bookAuthor.authorName[last] == '\n') {
        bk->bookAuthor.authorName[last] = 0; // read whole line
    }
    else ; // terminated early
    

    您还可以使用fscanf 限制字符,也可以读取空格,使用:

    char c;
    scanf(file, "%60[^\n]%c", bk->bookAuthor.authorName, c);
    
    if (c=='\n') {
        // we read the whole line
    } else {
        // terminated early, c is the next character
        //if there are more characters, they are still in the buffer
    }
    

    要丢弃该行的其余部分,您可以执行以下操作

    while (c != '\n' && c != EOF) c = fgetc(file);
    

    【讨论】:

    • fscanf(file,"%s", bk->bookAuthor.authorName); 不会扫描到 W. Richard Stevens 和 2) fgets(bk->bookAuthor.authorName, 60, file); 将不必要地将 \n 附加到作者的姓名。两种方法都不能解决 OP 的帖子。注意:字符串永远不会“尚未终止”。 char 数组通常不是以空字符结尾的。
    猜你喜欢
    • 1970-01-01
    • 2010-12-20
    • 2013-12-21
    • 2017-03-08
    • 2020-01-20
    • 2010-09-29
    • 2020-07-08
    • 1970-01-01
    相关资源
    最近更新 更多