fwrite question

This is a discussion on fwrite question within the C Programming forums, part of the General Programming Boards category; I have a string which i declare like this : char string[60]="Hello"; fwrite(string, sizeof(string), 1, file); the problem is, when ...

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    147

    fwrite question

    I have a string

    which i declare like this :

    char string[60]="Hello";

    fwrite(string, sizeof(string), 1, file);


    the problem is, when writing to the file, it not only writes hello, but it also includes the remaining elements which have not been initialised...which leaves me with 50 over other spaces in the file...

    i know u would say why not just do

    char string[5]="Hello";
    but i just want to allocate more in the buffer so i can add more characters in the future...
    Only by the cross are you saved...

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,386
    Instead of writing the whole size of the buffer, i.e. 60 chars, to the file, you could consider writing only 5 characters to the file. To make it a bit more general, you could first use strlen() to get the length of the string being stored in your buffer and then use this value for fwrite().

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Or you could use fprintf.

    >>it also includes the remaining elements which have not been initialised<<
    Not so, they have been initialised to \0.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Registered User
    Join Date
    Jun 2003
    Posts
    147
    okok, i'll give it a try...
    Only by the cross are you saved...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about fwrite under win32 platform
    By naruto in forum C Programming
    Replies: 2
    Last Post: 08-16-2004, 07:30 AM
  2. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  4. Question about linked lists.
    By cheeisme123 in forum C++ Programming
    Replies: 6
    Last Post: 02-25-2003, 12:36 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 12:47 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21