#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main( void )
{
        int fd,nob;
        char str[1024];
        fd = open("test.txt",O_RDWR|O_CREAT,S_IRWXU);
        if (fd < 0) {
                perror("open:");
                exit(0);
        }

        nob = write(fd,"hello first",1024);
        close(fd);

        printf(" %d nob written",nob);

        fd = open("test.txt",O_RDWR);
        nob = read(fd,str,1024);
        close(fd);

        printf(" %d nob read",nob);
        printf(" %s \n", str);
return 0;
}

The above code outputting 1024 nob written 1024 nob read hello first on the terminal.

when i say cat test.txt the file contents are hello first %d nob written %d nob read %s i heard about buffering , is it because of that , but i am closing the files immediately i finish the file operation.

any suggestions or help please...

Recommended Answers

All 3 Replies

You are telling the write call (which is not looking for null terminated strings) to write up to 1024 bytes but only providing 11 bytes to be written. write will happily try to continue to read from wherever "hello first" is stored in memory for 1024 bytes. Since constant strings are usually stored together in memory in an executable file you end up writing all of the constant strings from the program into your file.

To see what I mean, try the following change:

char msg[] = "hello first";
/* ... */
nob = write (fd, msg, 1024);

and examine what changes.

When you call write you need to provide the amount of data you want written exactly. So something like nob = write (fd, msg, strlen (msg));

Member Avatar for Mouche

You're using printf correctly with the format specifiers (such as %d), but the data you're seeing in the file is a bit of gibberish.

In your write command, the buffer you specify to write is a string "hello first" (length of 11), but you give it a write size of 1024. This means that it writes 1024 bytes from the start of the "hello first" string. This includes the string and the following 1013 bytes in memory.

To fix this, you should make the write size the same size as the string:

nob = write(fd,"hello first",11);

EDIT: Whoops, I was writing while L7Sqr posted.

Thank you L7Sqr and LaMouche for your explanation.

i dint know that "write" behaviour, its too dangerous.

Thank you very much..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.