[SOLVED] Getting invalid characters while writing to file using system c


I used a basic file descriptor program to open a file and write text in it closed it. but when I check the file it has some additional things written to it attaching my code and image pls refer.

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

This is out.txt file


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 – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.