从文本文件中读取一行到c中的字符数组

时间:2015-10-11 02:07:57

标签: c arrays io

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

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

我尝试编写一个fillin函数,它接受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);
}

File book.txt包含以下数据:

UNIX Network Programming
W. Richard Stevens
0131411551

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

1 个答案:

答案 0 :(得分:0)

以下行错误:

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

您还可以使用{<1}}限制字符,并使用以下方式读取空格:

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
}