Home > Blockchain >  Why am I getting extra characters when writing to a file from a string?
Why am I getting extra characters when writing to a file from a string?

Time:04-05

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

CodePudding user response:

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

CodePudding user response:

Try this and change your code as follows.

//bzero call is useless
write(fd, buff, strlen(buff));

the problem is that you have to write the exact number of bytes into the file, so you must use the strlen function, which counts the characters on a string till the first \0, which in this case is automatically placed after the \n by the compiler (see this).

  • Related