Reputation: 3
Can someone please tell me how basic file input and output is supposed to be performed in C. I tried searching but I could get only solutions for C++ etc.
I am trying to use fscanf and fprintf to do this. However, the program crashes as soon as it executes this part with the error message saying: "Unhandled exception at 0x50D39686 (msvcr120d.dll) in Test Project.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC." The file cats.txt is in location Documents\Visual Studio 2013\Projects\Test Project\Test Project My code is pasted below
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
double things_in_file[6];
int counter;
FILE *file_cats;
if ((file_cats = fopen("cats.txt", "r")) == NULL)
{
printf("This file doesn't exist.\n");
system("pause");
exit(-1);
}
for (counter = 0; counter <= 5; counter = counter + 1)
{
fscanf(file_cats, "%lf\n", &things_in_file[counter]);
printf("%f\n", things_in_file[counter]);
}
fclose("file_cats");
system("pause");
exit(0);
}
I figured out what was wrong. The line fclose("file_cats")
should be fclose(file_cats)
. That fixes the issue for me.
Upvotes: 0
Views: 1334
Reputation: 40145
array declaration eg array[5]
is 5 element, index from 0 to 4 (0,1,2,3,4)
scanf
requires the address of the variable to store the value
Upvotes: 1