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

标签 c arrays io

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

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 数组。

最佳答案

以下行是错误的:

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

关于c - 将文本文件中的一行读取到c中的字符数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33060860/

相关文章:

c - 函数执行在遇到第一个 return 语句时不退出

arrays - Numpy reshape 余数抛出错误

c - 用 C 从文件中读取行和列

PHP数据库序列化数组问题

c++ - 我的数组出现错误,因为它被定义为单数整数

Java文件I/O问题: file now written by newBufferedWriter

io - 如何从 Rust 中的文件中读取结构?

c++ - 如果我在未使用的 pthread_t 上调用 pthread_join() 会发生什么?

c - 如何将代码的输出重定向到代码块中的 pdf 或文本文件?

c - 显示数组时c中的段错误