如何写在Linux下用C文件? [英] How to write a file with C in Linux?
本文介绍了如何写在Linux下用C文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要重写了Linux的CP命令。因此,这一计划会像#。/ a.out的originalfile copiedfile
。我可以打开该文件,创建新的文件,但不能写入新文件。没有被写入。可能是什么原因呢?
目前C code是:
的#include<&stdio.h中GT;
#包括LT&; SYS / types.h中>
#包括LT&; SYS / stat.h>
#包括LT&;&fcntl.h GT;
#包括LT&;&unistd.h中GT;INT主(INT ARGC,CHAR * AA []){
INT的fd,FD1;
炭缓冲器[100]; 如果(argc个!= 3){
的printf(用法:./a.out<原><复制和GT; \\ n);
返回-1;
} FD =开(AA [1],O_RDONLY,S_IRUSR);
如果(FD == - 1){
的printf(找不到文件\\ n);
返回-1;
}
FD1 =开(AA [2],O_CREAT | O_WRONLY,S_IRUSR);
如果(FD1!= - 1){
的printf(创建档案\\ n);
}
ssize_t供N;
而(N =读(FD,缓冲液,50)){
写(FD1,缓冲,N);
的printf(..写.. \\ n);
}
关闭(FD);
关闭(FD1);
}
解决方案
您需要编写()读()数据到新的文件:
ssize_t供NRD;
INT的fd;
INT FD1;FD =开(AA [1],O_RDONLY);
FD1 =开(AA [2],O_CREAT | O_WRONLY,S_IRUSR | S_IWUSR);
而(NRD =读(FD,缓冲液,50)){
写(FD1,缓冲,NRD);
}关闭(FD);
关闭(FD1);
更新:增加了适当的打开...
顺便说一句,在O_CREAT可以OR操作(O_CREAT | O_WRONLY)。实际上,您打开太多的文件句柄。只要做一次开放。
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);
}
解决方案
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.
这篇关于如何写在Linux下用C文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文