Sunday, April 10, 2022

[SOLVED] Why am I getting extra characters when writing to a file from a string?

Issue

My program opens a file descriptor with open, writes a string to the file using write, then closes the file descriptor. When I check the file contents, it has additional characters after the string. Visual Studio Code shows these as "␀" (a single codepoint with the letters "NUL"); a screenshot below shows exactly how they appear in VS Code. Why are these extra characters in the file?

// test.cpp

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

int main(){
    int fd = open("out.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
    char buff[BUFSIZ];
    bzero(buff, sizeof(buff));
    strcpy(buff, "This is a test message!\n");
    write(fd, buff, sizeof(buff));
    close(fd);
}

This is out.txt file


Solution

write(fd, buff, sizeof(buff)); writes out at least 256 bytes as that is the size of char buff[BUFSIZ]; and BUFSIZ (from <stdio.h>) is at least 256.

In addition to "This is a test message!\n", hundreds of null characters are also written. For OP, they show up as "some additional things". @Some programmer dude

If only "This is a test message!\n" is desired, do not write hundreds of bytes, but only the length of the string. @SwirlyManager75

// write(fd, buff, sizeof(buff));
write(fd, buff, strlen(buff));


Answered By - chux - Reinstate Monica
Answer Checked By - David Marino (WPSolving Volunteer)