【发布时间】:2016-05-26 16:47:08
【问题描述】:
//编辑:我将第一个句柄的标志设置为 O_WRONLY,它应该是 O_RDONLY,这导致了问题。
我正在使用 C 语言在 Linux 中开发一个简单的程序,它将文本从一个文件复制到另一个文件。
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
...
int main(int argc, char * argv[])
{
int cp_from = open(argv[1],O_WRONLY);
int cp_to = open(argv[2],O_WRONLY|O_CREAT,0777); //make a descriptor for each file
int size = lseek(cp_from,0,SEEK_END); //check the size of the first file
lseek(cp_from,0,SEEK_SET) //return to the start of the file, don't know if that's needed
char *buf = (char*) malloc (size*sizeof(char)); //allocate enough memory to fit all text from 1st file into char array
read(cp_from,buf,sizeof(buf)-1); //read from the 1st file to the char array
printf("%s",buf); //print the buf
close(cp_from);
close(cp_to);
...
所以,稍后我会将“buf”写入()到“cp_to”,这样(希望)会起作用。但是,这里只有一半的工作,因为此时它停止工作,“buf”是空的,我不知道为什么。有任何想法吗?
【问题讨论】:
-
sizeof(buf)是char*大小。 -
请缩进您的代码。
-
这是我在 StackOverflom 上的第一个问题,我还不习惯这里格式化^^。我把“sizeof(buf)-1”改成了“size”,还是不行。
-
lseek()返回off_t而不是int。 -
“仍然不起作用”没有用。解释结果以及您的期望。