User__1
User__1

Reputation: 21

Why my code does not write the results to the file?

I am writing a code that reads the characters from a file, and then if one of these characters is 'A' it should be changed to 'Z', after these changes are made it should write it back to the file (not append, but write), but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me (since I tried correcting it by making some changes, here is the code I have so far:

int main(){
    char variable1[2000000];
    FILE *filePointer1;
    FILE *filePointer2;
    int counter;
    int exact_char_numb;

    filePointer1 = fopen("File.txt", "r");
    filePointer2 = fopen("File.txt", "w");
    fread(variable1,2000000,sizeof(char), filePointer1);

    for(counter = 0; counter<= 2000000 ; counter ++){
        if(variable1[counter] == 'A'){
            variable1[counter] = 'Z';
        }
        if(variable1[counter] == '+'){
            exact_char_numb = counter; // I am using '+' to mark the end of
        }                              // the file (for now)
    }

    fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);

    printf("%s\n", variable1);
    printf("%d\n", exact_char_numb);

    return 0;
}

Upvotes: 0

Views: 55

Answers (2)

"but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me..."

You should check whether the opening of the streams to file.txt were successful by checking the returned pointers for a null pointer before doing any operations with the streams:

if (!(filePointer1 = fopen("File.txt", "r")))
{
    fputs("Error occurred at opening file to read!", stderr);
    exit(1);
}

if (!(filePointer2 = fopen("File.txt", "w")))
{
    fputs("Error occurred at opening file to write!\n", stderr);
    exit(1);    
}

Furthermore, you don´t need to do have two pointers to two different streams. Use r+ mode:

if (!(filePointer = fopen("File.txt", "r+")))
{
    fputs("Error occurred at opening file!", stderr);
    exit(1);
}

Upvotes: 0

lenik
lenik

Reputation: 23556

In this call:

fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);

the variable exact_char_numb is likely equal to zero, so you don't get any output. You should turn on all warnings and the compiler will complain to you about the variables that can be used without initializing them first.

Upvotes: 3

Related Questions