gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:10:01 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com