C:从文件中读取一行时出现分段错误
我正在编写一个函数,它接受一个文件指针并从中删除几行。该文件的格式如下C:从文件中读取一行时出现分段错误,c,io,segmentation-fault,C,Io,Segmentation Fault,我正在编写一个函数,它接受一个文件指针并从中删除几行。该文件的格式如下 student1_ID firstName lastName numCourses course1 course2 ... student2_ID ... 我用来解决这个问题的方法是让用户输入我想删除的学生。然后我找到那个学生的ID,忽略接下来的三行,直到我得到那个学生的课程数。将该行转换为数字,然后读入该行数。否则,每隔一行将其复制到新文件中。最后,我返回一个指向新文件的指针 然而,由于某种原因,我得到了一个错误 这是我
student1_ID
firstName
lastName
numCourses
course1
course2
...
student2_ID
...
我用来解决这个问题的方法是让用户输入我想删除的学生。然后我找到那个学生的ID,忽略接下来的三行,直到我得到那个学生的课程数。将该行转换为数字,然后读入该行数。否则,每隔一行将其复制到新文件中。最后,我返回一个指向新文件的指针
然而,由于某种原因,我得到了一个错误
这是我的密码:
//This function delets lines from a file that are associated with a certain student
FILE *deleteStudent(FILE *fptr){
FILE *fptr2; //Pointer to a new file
int i = 0;
char c[40], line[40], s = '\n';
printf("Which stduent would you like to delete? \n");
while((c[i] = getchar()) != s){
i++;
}
while(!feof(fptr)){ //While not at end of file
fgets(line, 40, fptr); //Get a line
if(strcmp(line, c) == 0){ //If it matches user input, keep reading until next student
for(int i = 0; i < 3; i++){ //Reads student ID, first name, last name, # of courses
fptr2 = fopen("studentlist.txt", "r");
}
int numcrs = (int)line[0];
for(int i = 0; i < numcrs; i++){ //Reads through student's list of courses
fptr2 = fopen("studentlist.txt", "r");
}
}
else{ //Otherwise, copy the line to the new file
fptr2 = fopen("newfile.dat", "a");
fprintf(fptr2, "%s", line);
fclose(fptr2);
}
}
return fptr2; //Return the a pointer to the new file
}
我将非常感谢你的帮助
谢谢阅读要删除的学生后,您必须以null终止字符串
c
。否则,strcmp
将通过数组的结尾运行,试图找到字符串的结尾。在将nul终止符传递给strcmp
之前,您没有将nul终止符写入char c[40]
,可能还有其他错误。无论如何,fgets
会保留最后的换行符,但会被您的循环拒绝。@JimLewis,谢谢。在第一个while循环之后,我添加了c[I++]=0;这应该解决这个问题。然而,我仍然得到相同的segfault错误和相同的输出。@WeatherVane。我做出了上述评论中所述的更改。尽管如此,我还是犯了同样的错误。
$ ./my.prog
Which stduent would you like to delete?
111111111
Segmentation fault (core dumped)