How do I write a string into a file in C without writing (null)?

Advertisements

This is what I have got:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(int argc, char* argv[]) {
    
    unsigned short index;
    
    srand(time(NULL));
    index = rand(); 

    char * task = "";
    
    unsigned short i=0;
    
    for (; i < strlen(task); i+=task[i]) ;

    index = (index + i) % 999;

    FILE * file = fopen("file.txt", "a+");
    fprintf(file, "%03hu", index);
    
    for (unsigned short i=1; i<=argc; i++) {
        fprintf(file, " %s", argv[i]);
    }
    
    fwrite("\n", 1, 1, file); // was a solution to a similar question, still prints null characters
    // fprintf(file,"\n") and fputs(file,"\n") also print a null character into a file

    fclose(file);
}

When I read the file using cat I can see (null) at the end of lines. Example:

559 asd (null)
035 asd (null)
065 asd (null)
790 asd (null)
799 asd (null)

I have tried googling. Found one answer but it does not work.

>Solution :

Nothing in your code outputs a null byte to the output file. The file contains the characters (null) at the end of the lines. The reason for this is the loop iterates up to and including argc, hence you use printf to output argv[argc], which is a null pointer, and on your target system, fprintf outputs the string "(null)" in this case. Use a standard loop instead:

for (int i = 0; i < argc; i++) {
    fprintf(file, " %s", argv[i]);
}
fprintf(file, "\n");

No need to use "a+" mode in fopen, "a" will suffice as you never read from this file.

The line for (; i < strlen(task); i+=task[i]) ; is highly suspect, but since task points to an empty string, the loop exits immediately.

To output a portion of a string or one without a null terminator, you can use fwrite(s, 1, length, file) or printf("%.*s", length, str).

Leave a ReplyCancel reply