繁体   English   中英

将文本文件中的一行读入c中的字符数组

[英]Reading a line from a text file into an array of characters in c

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

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

文件book.txt具有以下数据:

UNIX Network Programming
W. Richard Stevens
0131411551

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

以下行是错误的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM