[英]How to write a file with C in Linux?
我想重寫Linux的“cp”命令。 所以這個程序會像#./a.out originalfile copiedfile
一樣工作。 我可以打開文件,創建新文件,但不能寫入新文件。 什么都沒寫。 可能是什么原因?
當前的 C 代碼是:
#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);
}
您需要將 read() 數據寫入()到新文件中:
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);
更新:添加了正確的打開...
順便說一句,O_CREAT 可以被 OR'd (O_CREAT | O_WRONLY)。 您實際上打開了太多文件句柄。 只需打開一次。
首先,您編寫的代碼不可移植,即使您可以使用它。 當有一種完全獨立於平台的方法時,為什么要使用特定於操作系統的函數? 這是一個僅使用單個頭文件並且可移植到任何實現 C 標准庫的平台的版本。
#include <stdio.h>
int main(int argc, char **argv)
{
FILE* sourceFile;
FILE* destFile;
char buf[50];
int numBytes;
if(argc!=3)
{
printf("Usage: fcopy source destination\n");
return 1;
}
sourceFile = fopen(argv[1], "rb");
destFile = fopen(argv[2], "wb");
if(sourceFile==NULL)
{
printf("Could not open source file\n");
return 2;
}
if(destFile==NULL)
{
printf("Could not open destination file\n");
return 3;
}
while(numBytes=fread(buf, 1, 50, sourceFile))
{
fwrite(buf, 1, numBytes, destFile);
}
fclose(sourceFile);
fclose(destFile);
return 0;
}
編輯: glibc 參考有這樣的說法:
一般來說,你應該堅持使用流而不是文件描述符,除非你想要做一些只能在文件描述符上完成的特定操作。 如果您是初學者並且不確定要使用哪些函數,我們建議您專注於格式化輸入函數(參見格式化輸入)和格式化輸出函數(參見格式化輸出)。
如果您擔心程序在 GNU 以外的系統上的可移植性,您還應該意識到文件描述符不像流那樣可移植。 您可以期望任何運行 ISO C 的系統都支持流,但非 GNU 系統可能根本不支持文件描述符,或者可能僅實現對文件描述符進行操作的 GNU 函數的子集。 然而,GNU 庫中的大多數文件描述符函數都包含在 POSIX.1 標准中。
您必須在與read
相同的循環中write
。
您必須使用 mallock 分配緩沖區,並為讀寫提供指向它的指針。
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
ssize_t nrd;
int fd;
int fd1;
char* buffer = malloc(100*sizeof(char));
fd = open("bli.txt", O_RDONLY);
fd1 = open("bla.txt", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,sizeof(buffer))) {
write(fd1,buffer,nrd);
}
close(fd);
close(fd1);
free(buffer);
return 0;
}
確保 rad 文件存在並包含某些內容。 它並不完美,但它有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.