I am working on unix system calls
.
I want to read the string
from standard input
using read()
and then write it to the file using write()
.
I am able to open
the file , read
the string
from standard input
, but unable to write
it to the file.
my code is :
#include <unistd.h> // to remove WARNINGS LIKE warning: implicit declaration of function ‘read’ , warning: implicit declaration of function ‘write’
#include<fcntl.h> /* defines options flags */
#include<sys/types.h> /* defines types used by sys/stat.h */
#include<sys/stat.h> /* defines S_IREAD & S_IWRITE */
#include<stdio.h>
int main(void)
{
int fd,readd;
char *buf[1024];
fd = open("myfile",O_RDWR);
if(fd != -1)
printf("open error\n");
else
{
// read i\p from stdin , and write it to myfile.txt
if((readd=read(0,buf,sizeof(buf)))<0)
printf("read error\n");
else
{
printf("\n%s",buf);
printf("\n%d",readd);
if(write(fd,buf,readd) != readd)
printf("write error\n");
}
}
return 0;
}
the output is
write error
it is working properly , if I write
the string
to standard output
Question :
1) what is the problem with write()
?
2) I want to include newline character \n
at the end of the line. How is it possible through standard input
?