cgccc99

How do I write command line arguments into a file in C without writing (null)?


I need to output the arguments passed to a program into a file. Every time I do it, it outputs (null) at the end of every line.

This is what I have got:

#include <stdio.h>

int main(int argc, char *argv[]) {
    FILE *file = fopen("file.txt", "a+");
    
    for (int i = 1; i <= argc; i++) {
        fprintf(file, " %s", argv[i]);
    }

    fputs("\n", file); // add newline at the end

    fclose(file);
}

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

 asd def (null)
 second test (null)

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).