0

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.

6
  • 1
    counter <= 5 should be counter < 5 and fscanf ... &things_in_file[counter] Commented Dec 7, 2013 at 16:15
  • @BLUEPIXY - Your comment should be an answer. And tell the OP that he is overrunning the array buffer. Commented Dec 7, 2013 at 16:17
  • 4
    The fact that you program in MS VS 2013 is irrelevant for this question. Reading from files is standard and should work regardless of the IDE. Commented Dec 7, 2013 at 16:25
  • I just changed the dimension of the array from 5 to 6. But I still get this error message: "Unhandled exception at 0x50F79686 (msvcr120d.dll) in Test Project.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC." Commented Dec 7, 2013 at 18:36
  • Sorry, I just noticed the comment pointning ou the missing "&" in fscanf function. I fixed that too. I do get the values from cat.txt listed in the black window, but I get this message soon after: "Unhandled exception at 0x50DC7EEB (msvcr120d.dll) in Test Project.exe: 0xC0000005: Access violation writing location 0x00EE58D8." Commented Dec 7, 2013 at 18:38

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.