Wrting "Null" Values into File

For everyone, just starting with C++ or programming at all. Ask newbie questions in this forum!

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

Wrting "Null" Values into File

Postby eng01015 » Mon Sep 29, 2003 7:17 am

Hi to all,

I need to write data into a file of such format

wd (I can do this)
ht (I can do this)
x x x x x x x ... x (How do I do this?)

where the x's represent NULL char values.

Using fprintf(filename, "%c", ...) or something like that, how can I print the NULL values?

Thx in Adv,
Julian.
eng01015
 
Posts: 8
Joined: Mon Sep 29, 2003 7:12 am

Re: Wrting "Null" Values into File

Postby raimo » Mon Sep 29, 2003 7:54 am

eng01015 wrote:Using fprintf(filename, "%c", ...) or something like that, how can I print the NULL values?

You cannot use fprintf for that purpose because by definition it writes the string without trailing '\0':s.
As you use C the fwrite function should work for you.

fwrite man page:

size_t fwrite(const void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);

The function fwrite() writes nmemb objects, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.

The function fwrite() returns a value less than nmemb only if a write error has occurred.
User avatar
raimo
 
Posts: 372
Joined: Fri Sep 26, 2003 6:50 am
Location: Finland

Writing "NULL" Values into Files

Postby eng01015 » Mon Sep 29, 2003 10:31 am

hi again,

May I know what would the 'NULL' chars look like if i write it to a .txt file? Is it just blank spaces, or should it be "squares"?

Thx again!
Julian.
eng01015
 
Posts: 8
Joined: Mon Sep 29, 2003 7:12 am

Re: Writing "NULL" Values into Files

Postby raimo » Mon Sep 29, 2003 10:43 am

eng01015 wrote:May I know what would the 'NULL' chars look like if i write it to a .txt file? Is it just blank spaces, or should it be "squares"?


It depends on how you show them on the screen in your program or which editor you use to open the file.
For example, editor called VIM on Unix will show "^@" marks meaning NULL in a file. I'm kinda interested to know how windows notepad handles that situation, try this program:
Code: Select all
#include <stdio.h>

int main () {
        char ptr[] = "this is a \0string\0";
        FILE *fp;
        fp=fopen("string.txt","w");
        fwrite(ptr,1,18,fp);
        fclose(fp);
}

Run it and open "string.txt" using Notepad and see what happens. Try changing "w" to "wb" and see what's the difference. On Unix this makes no difference at all, binary and text are handled the same way.
User avatar
raimo
 
Posts: 372
Joined: Fri Sep 26, 2003 6:50 am
Location: Finland


Return to For Beginners

Who is online

Users browsing this forum: Google [Bot] and 1 guest