//编辑:我将第一个句柄的标志设置为 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);
...
所以,稍后我会 write() 将“buf”写入“cp_to”,这(希望)会起作用。但是,这里只有一半的工作,因为它此时停止工作,“buf”是空的,我不知道为什么。有任何想法吗?
最佳答案
这里有一些评论要点:
- Don't cast the return value of
malloc()
in C . - 不要在堆指针上使用
sizeof
,认为它会返回与分配的缓冲区大小有关的任何内容;它不会。您将获得指针的大小。 - 使用正确的类型,而不仅仅是
int
用于所有内容。类型很重要,并非所有类型都像int
。 - 不要将从文件中读取的随机数据视为字符串。
- 不做 I/O 也不检查返回值。 I/O 可能会失败。
- ...内存分配也是如此。
最好使用一个小的(或更小的)固定大小的缓冲区,并在循环中读/写。这样,无论文件大小如何,您的程序都会使用有限的内存。
关于c - (C Linux) 中的 read() 和缓冲区大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466751/