简体   繁体   中英

Read and write in c++

I am trying to use the system calls read() and write(). The following program creates a file and writes some data into it. Here is the code..

int main()
{
    int fd;
        open("student",O_CREAT,(mode_t)0600);

    fd=open("student",O_WRONLY);
    char data[128]="Hi nikhil, How are u?";

    write(fd,data,128);

}

Upon the execution of the above program i got a file with name student created with size as 128 bytes.

int main()
{
    int fd=open("student",O_WRONLY);
    char data[128];
    read(fd,data,128);
    cout<<(char*)data<<endl;
}

But the output i get is junk characters....why is this so?

I wrote a small read program to read data from the file. Her is the code.

But the output

Don't read from a file that you've open in O_WRONLY mode!

Do yourself a favor and always check the return values of IO functions .

You should also always close file descriptors you've (successfully) open ed. Might not matter for trivial code like this, but if you get into the habit of forgetting that, you'll end up writing code that leaks file descriptors, and that's a bad thing.

You're not checking whether read() returns an error. You should do so, because that's probably the case with the code in your question.

Since you're opening the file write-only in the first place, calling read() on it will result in an error. You should open the file for reading instead:

char data[128];
int fd = open("student", O_RDONLY);
if (fd != -1) {
    if (read(fd, data, sizeof(data)) != -1) {
        // Process data...
    }
    close(fd);
}

Well, one of the first things is that your data is not 128 bytes. Your data is the string: "Hi nikhil, How are u?", which is way less than 128 bytes. But you're writing 128 bytes from the array to the file. Everything after the initial string will be random junk from memory as the char array is only initialized with 21 bytes of data. So the next 107 bytes is junk.

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