Search code examples
cfwrite

fwrite a pid_t not working


I have the follwoing code:

...
printf("Started %d", pid);
FILE * fh;
fh = fopen("run/source.pid", "wb");
fwrite(&pid, sizeof(int), 1, fh);
fclose(fh);

However the written pid file writes jargon, and not the integer, I though pid_t was just an int, I even tied doing sizeof(pid_t) for the second argument I get similar issues.

Any ideas? Thanks for the help in advance.

Thanks


Solution

  • well I do not understand quite well the question (too little context), but the issue may be is that you are seeing the file in a text editor, terminal, etc..

    fwrite() writes raw data, for example, suppose you have a pid number, lets say 12, and you write that number using fwrite like this:

    fwrite(&pid, sizeof(int), 1, file);
    

    fwrite() will write a 32 bit integer into the file file, that is, depending in your processor type, a byte sequence like this: 00 00 00 12

    However

    fprintf() will write a byte sequence of : 49 50 (ASCII characters platform independent) visible among all terminals or text editors.

    Hope this helps.