File Input and Output


  1. Declare a file pointer, fi

  2. Using this file pointer, open the text file file.txt for reading only.

  3. Add code to check that the file has been opened correctly.

  4. How would the code for question 2 be changed if you wished to oen the file for wwriting rather than reading.

  5. Assuming that the file file.txt opened for reading contains a column of integers, give some example to code to read all the numbers into an array.


Answers





























































  1. FILE *fi;

  2. fi = fopen("file.txt", "r");

  3. if ((fi = fopen("file.txt","r")) == NULL ) 
    {
             fprintf(stderr,"Can't open file file.txt for reading\n");
             exit(1);
    }
    
  4. fi = fopen("file.txt", "w");

  5. fscanf(fi, "%d", &array[i]);
    while (!feof(fi))
    {
    	i++;
    	fscanf(fi,"%d",&array[i]);
    }
    


    Back to Questions Back to Main Page for Lecture 8