-2

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

ThePhycho
  • 11
  • 1
  • 1
    I'm not sure how VSCode has anything to do with this issue; It's not the cause of bugs in code.... – Claies Mar 07 '23 at 01:07
  • So, my code specifically is the problem, got it. Do you have any idea as to why. I'm not 100% sure where the fault lies. – ThePhycho Mar 07 '23 at 01:12
  • Have you tried [debugging your program yourself](//stackoverflow.com/q/25385173/11107541)? Doing some debugging can help you provide a [mre]. – starball Mar 07 '23 at 01:15
  • The code seems to work fine on https://onlinegdb.com/xumw6yXTR If I had to guess, I would say that your `Grades.txt` file is not in the same folder as your project, or is named incorrectly (Case sensitive on mac/linux, maybe?). It's not exactly obvious from what you've posted. also, `file\a.exe` looks like maybe you have compiler options putting your exe in a subfolder where the file isn't located? All just guesses. – Claies Mar 07 '23 at 01:21
  • Ah i see, i'll try and narrow down my question next time. Thanks for the assist – ThePhycho Mar 07 '23 at 01:21

1 Answers1

0

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.

kiwi
  • 41
  • 4