How to write a file with C in Linux?

c, linux

Solution

You need to write() the read() data into the new file:

ssize_t nrd;
int fd;
int fd1;

fd = open(aa[1], O_RDONLY);
fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,50)) {
    write(fd1,buffer,nrd);
}

close(fd);
close(fd1);

Update: added the proper opens...

Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.

Problem

I want to rewrite the "cp" command of Linux. So this program will work like `#./a.out originalfile copiedfile`. I can open the file, create new file but can't write the new file. Nothing is written. What could be the reason? The current C code is: ``` #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc,char *aa[]){ int fd,fd1; char buffer[100]; if(argc!=3){ printf("Usage : ./a.out <original> <copy> \n"); return -1; } fd=open(aa[1],O_RDONLY,S_IRUSR); if(fd==-1){ printf("file not found.\n"); return -1; } fd1=open(aa[2],O_CREAT | O_WRONLY,S_IRUSR); if(fd1!=-1){ printf("file is created.\n"); } ssize_t n; while(n=read(fd,buffer,50)){ write(fd1,buffer,n); printf("..writing..\n"); } close(fd); close(fd1); } ```

Original source