-1

I have written this code in an attempt to read a .txt file. I am getting the following outcome when trying to run it...

int main()
{
FILE *pToFile = fopen("Marks.txt", "r");

int line = 0;
int num;

char Students[100];

for (int i = 0; i < 100 && ( fscanf(pToFile, "%d" , &num) == 1); ++i)
{
    Students[line] = num;
    printf("%d", Students[line]);
}

fclose(pToFile);
}

I am unsure how to solve this issue. Many thanks

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tom Adams
  • 3
  • 3

2 Answers2

0

Here

Students[line] = num;

Line doesn't change i.e it always 0, so either increment it or use loop variable. For e.g

for(int i = 0; i < 100 && ( fscanf(pToFile, "%d", &num) == 1); ++i) {
        Students[i] = num
        printf("%d ", Students[i]); 
}

And always check the return value of fopen() to knwo whether call to fopen() was success or not. For e.g

File *pToFile = fopen("Marks.txt","r");
if(pToFile == NULL) {
   /* @TODO error handling */
   return 0;
}
Achal
  • 11,821
  • 2
  • 15
  • 37
0

It is very likely that Marks.txt is not located in the directory where the executable generated by the IDE wants to load it. Consequently, pToFile will get NULL and the subsequent fscanf will fail.

Always test the result of fopen, e.g. like

FILE *pToFile = fopen("Marks.txt", "r");
if (!pToFile) {
   printf("failed to open file.");
   return 1;
}
...

And place Marks.txt in the directory where XCode generated the executable. You get this easily in XCode by right-clicking - under the Products-Tree - on your product and choose "Show in Finder":

enter image description here

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58