0

I've been having issues with fscanf. In my code, I specify the name of the text file I am trying to load, but Xcode give me the EXC_BAD_ACCESS error whenever I try to use fscanf. The file I am trying to load is in the same directory as the code. What am I doing wrong?

int main(int argc, char *argv[]) {

int grid[9][9], i, j;
char inputfilename[40];
FILE *fp;

printf("Enter filename: ");
scanf("%s",&inputfilename[0]);

fp = fopen(inputfilename, "r");

for (i = 0; i < 9; i++) {
    for (j = 0; j < 9; j++) {
        fscanf(fp, "%d", &grid[i][j]);
        }
    }

return 1;
}
  • 1
    you need to check if fopen returned valid file descriptor or not – Pras Oct 31 '17 at 06:34
  • Actually, `fopen()` never returns a file descriptor; it returns a file stream or `FILE *`, while functions like `open()` return file descriptors. However, you're correct that the code should check whether the file was opened successfully before continuing. Indeed, it should check that the file name was read, and that the numbers were read — the `scanf()` call and the `fscanf()` call should both be checked. Eventually, you'll get used to the fact that a lot of C coding is about checking for errors returned by functions that you call. – Jonathan Leffler Oct 31 '17 at 06:43
  • If you don't use either `argc` or `argv`, use `int main(void)` as the program signature. – Jonathan Leffler Oct 31 '17 at 06:44

0 Answers0