//编辑:我将第一个句柄的标志设置为O_WRONLY,它应该是O_RDONLY,这导致了问题。
我正在使用C语言在Linux上编写一个简单程序,将文本从一个文件复制到另一个文件。
sw.js
所以,稍后我会将“buf”写入“cp_to”,这将(希望)有效。但是,这里只有一半的工作因为它在此时停止工作,“buf”是空的,我不知道为什么。有任何想法吗?
答案 0 :(得分:1)
以下是一些评论点:
malloc()
in C。sizeof
,因为它会返回与分配的缓冲区大小有关的任何内容;它赢了。你将获得指针的大小。int
。类型很重要,并非所有类型都像int
。使用小型(或小型)固定大小的缓冲区并在循环中读/写可能更好。这样,无论文件大小如何,程序都会使用有限的内存量。
答案 1 :(得分:0)
以下代码:
argc
的警告(请参阅评论)现在是代码
//#include <sys/types.h>
//#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
int cp_from = open(argv[1], O_RDONLY);
int cp_to = open(argv[2], O_WRONLY|O_CREAT,0777);
//make a descriptor for each file
size_t size = (size_t)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 = malloc (size); //allocate enough memory to fit all text from 1st file into char array
read( cp_from, buf, size ); //read from the 1st file to the char array
write( cp_to, buf, size ); //print the buf
close(cp_from);
close(cp_to);
}