user696977
user696977

Reputation: 105

Problem with writing to file in C

I'm trying to write some information to a file in C and was never running into a problem before. However, now it seems to break when writing a variable's contents to file. Here is what I have.

    int i, count = 0;
    FILE *f;
    int _x, _y, _z, _x2, _y2, _z2;

    for (i = 0; i < HEIGHT * WIDTH*3; i+= 3)
    {
        if (buffer1[i/3] < MAGIC_VALUE)
        {
            count++;
        }

        if (buffer2[i/3] < MAGIC_VALUE)
        {
            count++;
        }
    }

    printf("Count = %d\n", count); // prints correctly...
    f = fopen("file.abc", "w");
    fprintf(f, "lots\n of\n text\n");

    fprintf(f, "count: %d\ntext \ntext y\ntext text text", count); // crashes here
    fprintf(f, "\nend");

    fclose(f);

Why is this line crashing? It ends up in dbghook.c at the line that says _debugger_hook_dummy = 0;

The crash is occurring when printing count to the file, but if I take out that print, it will crash when printing the last statement. The first one seems to be printing fine, though..

When I print the error, I get "Too many open files"

Upvotes: 2

Views: 3468

Answers (2)

William Pursell
William Pursell

Reputation: 212178

1st step: replace

f = fopen( path, mode );

with

f = fopen( path, mode );
if( f == NULL ) {
    perror( path );
    exit( EXIT_FAILURE );
}

Upvotes: 1

iehrlich
iehrlich

Reputation: 3592

As for MSVS2008, all works fine. Of course, the 'for' loop was to be commented since used global variables and defines.

First, you should try to do something like

#include <iostream>

void main()
{
    int count = 0;
    FILE *f;

    f = fopen("file.abc", "w");   
    fprintf(f, "count: %d\n", count);  
    fclose(f);
}

and see what happens.

Upvotes: 0

Related Questions