c - Segmentation fault occurring at very straight-forward part of the code -


When I run the program for the first time (the output file is not created yet), it works fine. But when I run it again (the output file is present), it makes a split mistake after reading the final input.

By looking at the problem, it seems that there is something to do with my file handling, but when I tried to debug, I found out that I got a CG. Main () . The mistake before leaving the loop in

  #include & lt; Stdio.h & gt; # Defined EMPS 3 structure employee {four first names [40]; Four last names [40]; Int id; }; Typedef struct employee employee; / * Interactive employee data input from the keyboard * / zero InputEmployeeRecord (employee * ptrEmp); / * Display the contents of a given employee record * / Zero PrintEmployeeRecord (Constant Employee E); / * Save the contents of the employee record list in the newly created text file specified by filename * * / Zero retirement record (Constant and [], Const four * filename); Int id = 0; Int main () {employee employee [emps]; For (int i = 0; i  First Name); Printf ("Enter last name \ n"); Scanf ("% s", ptrEmp-> Last Name); PtrEmp- & gt; Id = ++ id; } Zero PrintEmployeeRecord (Constant Employee E) {printf ("employee% d:% s% s \ n", e.id, e.firstname, e.lastname); } Zero seamorrheck record (Constant employee and [], const char * filename) {FILE * fptr = fopen (filename, "R"); / * File does not exist * / if (fptr == faucet) {fclose (fptr); // file FILE * fptr2 = fopen (filename, "w"); Fclose (fptr2); // continue reading fptr = fopen (filename, "r"); } Char firstLetter; Int headerExists = 0; If (FIFT (FPTR)) {FSCNF (FTPR, "% C", First Lighter); If (first litter == 'I') headerexists = 1; } Fclose (fptr); File * fptr2 = fopen (filename, "a"); If (! HeadExists) fprintf (fptr2, "id first name LASTNAME"); (Int i = 0; i & lt; emps; i ++) fprintf (fptr2, "\ n% d% s% s", e [i]. Id, e [i]. First name, e [i] .lastname); Fclose (fptr2);   

[originally code]

The problem is probably incorrect < Code> fscanf (fptr, "% c", first letter); On . % C input is expected as a four * when you are giving it a char (which is an integer in c).

To fix this, fscanf (fptr, "% c", and firstLetter);

In addition to calling fclose on an empty pointer is not recommended

Comments