Run into an issue with some code i wrote where i want to open a txt file and then display the name and grades of the people in said text file. The code i am using is as follows
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[10];
int marks[4];
};
int main()
{
struct student s[5];
int i=0;
FILE *fp=fopen("Grades.txt","r");
if(fp==NULL)
{
printf("Error Opening the input file\n");
return-1;
}
else
printf("File Opening successfully\n");
while(!feof(fp))
{
fscanf(fp,"%s", s[i].name);
for(int j=0; j<4; j++)
fscanf(fp,"%d", &s[i].marks[j]);
i++;
}
printf("The Grade details ....\n");
for(int i=0; i<5; i++)
{
printf("%s\n",s[i].name);
for( int j=0; j<4; j++)
printf("%d\n", s[i].marks[j]);
}
fclose(fp);
return 0;
}
No matter how i structure the code i get error file\a.exe' has exited with code -1 (0xffffffff).
If i have done something wrong please let me know!
Peter 55 66 44 67 Lilly 100 90 43 89 John 34 56 78 65 Mary 45 56 78 90 Alex 30 45 65 54
The program is likely returning -1 because it cannot open Grades.txt
:
FILE* fp = fopen("Grades.txt","r");
if (fp == NULL)
{
printf("Error Opening the input file\n");
return -1;
}
If you are running this from inside Visual Studio/Visual Studio Code it is likely that Grades.txt
does not exist in the same folder as the executable file.
If you really want to hardcode the filepath, try specifying an absolute path rather than a relative one: fopen("C:\Users\Example\Desktop\Grades.txt","r");
"Grades.txt"
by itself is a relative path, so it needs to exist in the same folder/directory as the program.