如何在c中忽略.txt文件中的换行符
我从一个文本文件中读取,并将每个元素存储到一个链接列表中。但是,当程序到达返回字符或换行符时,程序返回一个错误如何在c中忽略.txt文件中的换行符,c,C,我从一个文本文件中读取,并将每个元素存储到一个链接列表中。但是,当程序到达返回字符或换行符时,程序返回一个错误 从文本文件读取并存储到结构中。当我将每个结构打印到屏幕上时,我注意到了这个错误。程序在返回字符之前打印最后一个结构,然后退出 int main(int argc, const char * argv[]) { printf("Hello!\n"); char filename[] = "artist.txt"; print_artists(read_arti
从文本文件读取并存储到结构中。当我将每个结构打印到屏幕上时,我注意到了这个错误。程序在返回字符之前打印最后一个结构,然后退出
int main(int argc, const char * argv[]) {
printf("Hello!\n");
char filename[] = "artist.txt";
print_artists(read_artists(filename));
return 0;
}
struct artist *read_artists(char *fname)
{
int maxlen = 225;
int artid = 0;
int altartid = 0;
int pc = 0;
char artname[80];
char data[maxlen];
int valid = 0; // 0 acts as true 1 acts as false
int checkresult = 0; //checks result of sscanf
struct artist *temphead = create_artist(0,0,0,"0");
FILE *fp = fopen(fname ,"r");
if (fp != NULL)
{
while (fgets(data,maxlen,fp))
{
checkresult = sscanf(data,"%d\t%[^\t\n]\n",&artid,artname);
if (checkresult == 2)
{
struct artist *b = NULL;
b = create_artist(artid,altartid,pc,artname);
temphead = add_artist(temphead,b);
}
else
{
printf("error checkresult = %d\n",checkresult);
printf("break out of loop valid = 1\n");
valid = 1; // acts as boolean variable
break; //breaks out of the while(fgets)
}
}
fclose(fp);
return (temphead);
}
else
{
fclose(fp);
printf("File Error\n");
return (NULL);
}
}
void print_artists(struct artist *head)
{
if (head != NULL)
{
struct artist *temp = head;
while (temp -> next != NULL)
{
print_artist(temp);
temp = temp -> next;
}
print_artist(temp);
}
}
这是输出
我正在读取的文本文件
< p>当你到达Bodenstandig之前的空行时,sSCANF将不匹配,你将退出“while”的while循环。 如果sscanf未返回2,则应检查该行是否为空,如果为空,则跳过并读取下一行。或者跳过检查,忽略错误行。while(fgets(…)条件将在文件末尾变为false,因此不需要在错误的行上退出
if (checkresult == 2)
{
....
}
else
{
continue; // will go back to top while(fgets(...))
}
您是说程序错误还是说打印了
printf(“错误检查结果=%d\n,检查结果”);
?注意:最好不要在fp==NULL
时调用fclose(fp)
。程序错误中止6,我试图消除错误,这就是为什么我添加了dprintf(“错误检查结果=%d\n,检查结果”);“当我将每个结构打印到屏幕上时,我注意到错误,程序会在返回字符退出之前打印最后一个结构。”不清楚,因为发布的代码没有printf()使用print\u artists()
我希望void print\u artists(struct artist*head){while(head){print\u artists(head);head=head->next;}}