#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    2
    Rep Power
    0

    File handling (Writing data to a file)


    Below is a code for continuously overwrite the existing data and write the new data. However its not working for "w" mode.
    The program open the file but not writing into it.

    But When I am using append mode "a" or "a+" it work fines. Please any body help how can I make it work for "w" mode.


    #include <stdio.h>

    #include<stdlib.h>
    #include <windows.h>




    FILE *file;

    int main(void) {

    while(1)
    {
    FILE *file;
    char hello[15]={"hello world"};





    file = fopen("file1000.txt","w");

    if (file == NULL)
    {
    printf("Error opening file!\n");
    exit(1);
    }

    fprintf(file,"%s",hello);

    Sleep(5000);
    fclose(file);
    }


    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    Your program works fine for me. It opens the file discarding the previous contents, then writes "Hello World" and finally closes the file. Then it repeats the above forever.

    What indications do you have that the program didn't work?

    Did the file get created? This is possibly the only indication you'll have that the program is succeeding. You don't flush the output buffer so the data is only available for a few mili-seconds at most since it is not flushed until the fclose() and then it is immediately erased.

    In future please use code tags when posting code.

    You also don't need that global variable, get rid of it.

    Jim
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    2
    Rep Power
    0
    Thanks for your reply. After using fflush its working fine for me.

    Originally Posted by jimblumberg
    Your program works fine for me. It opens the file discarding the previous contents, then writes "Hello World" and finally closes the file. Then it repeats the above forever.

    What indications do you have that the program didn't work?

    Did the file get created? This is possibly the only indication you'll have that the program is succeeding. You don't flush the output buffer so the data is only available for a few mili-seconds at most since it is not flushed until the fclose() and then it is immediately erased.

    In future please use code tags when posting code.

    You also don't need that global variable, get rid of it.

    Jim

IMN logo majestic logo threadwatch logo seochat tools logo