简体   繁体   中英

Issue while writting the data using write system call in linux

I've written the example code for read,write system call in linux....Executed without any issues.

As a result,storing the buffer data into a file....

Expected result to be stored in a file is Hello World!..But i'm getting the data in a file like this Hello World!^@

What shall i need to do inorder to get the expected result?

int main(int argc , char *argv[])
{
        int fd;
        char buff[14];
        fd = open("myfile.txt",O_CREAT| O_WRONLY,0777);

        if(fd == -1)
        {
                printf("Failed to open the file to write");
                exit(0);
        }

        write(fd,"Hello World!\n",13);
        close(fd);

        fd = open("myfile.txt",O_RDONLY,0777);

        if(fd == -1)
        {
                printf("Failed to open the file to read");
                exit(0);
        }

        read(fd,buff,14);
        buff[14] = '\0';
        close(fd); 
        printf("Buff is %s\n",buff);

        return 0;
}

您声明buff为14个字符,但是在位置15处写了终止符。这导致了两个 未定义行为的实例:一个是因为您写出了数组的界限,另一个是因为当您打印缓冲区时,您有未初始化的数据位于位置14。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM