I am writing a function that takes a file pointer and deletes a few lines from it. The file is of the form
student1_ID
firstName
lastName
numCourses
course1
course2
...
student2_ID
...
The method I'm using to solve this is to take user input on what student I would like to delete. I then find that student's ID, ignore the next three lines until I get to the number of courses for that student. Convert that line to a number, and read in that number of lines. Otherwise, copy every other line to the new file. At the end, I return a pointer to the new file.
However, I'm getting a segfault for some reason.
Here's my code:
//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
}
The output is as follows
$ ./my.prog
Which stduent would you like to delete?
111111111
Segmentation fault (core dumped)
I would appreciate the help.
Thanks