Thread: Writing an integer into a file

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    1

    Writing an integer into a file

    Hi,

    I am new to C programming. I am trying to write an integer into a file using built-in fwrite function in C. After writing the integer into file it becomes unreadable(^@^@.. characters). Can you please let me know how to write an integer into a file so that it is readable ?. I am using the following code.
    Code:
    void main(){
        int a = 10;
        int *p = &a;
        FILE *fp = fopen("Ascii.txt", "w");
        fwrite(p,sizeof(int),1,fp);
        fclose(fp);
    }
    Regards,
    Srikkanth

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    What did you expect? There's a difference between the integer value 10 and its textual representation in ASCII. Use fprintf with the %d specifier if you want the integer to written as ASCII text.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    fwrite is for binary data. Normal text data is handled by

    Code:
    fprintf(NameOfFilePointer, "%d", myIntegerVariableName);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Trouble writing to file using fwrite()
    By yougene in forum C Programming
    Replies: 4
    Last Post: 12-30-2008, 05:13 PM
  3. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  4. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 10:51 PM