(C Linux)中的read()和缓冲区大小错误

时间:2016-05-26 16:47:09

标签: c linux file buffer

//编辑:我将第一个句柄的标志设置为O_WRONLY,它应该是O_RDONLY,这导致了问题。

我正在使用C语言在Linux上编写一个简单程序,将文本从一个文件复制到另一个文件。

sw.js

所以,稍后我会将“buf”写入“cp_to”,这将(希望)有效。但是,这里只有一半的工作因为它在此时停止工作,“buf”是空的,我不知道为什么。有任何想法吗?

2 个答案:

答案 0 :(得分:1)

以下是一些评论点:

  1. Don't cast the return value of malloc() in C
  2. 不要在堆指针上使用sizeof,因为它会返回与分配的缓冲区大小有关的任何内容;它赢了。你将获得指针的大小。
  3. 使用适当的类型,而不仅仅是int。类型很重要,并非所有类型都像int
  4. 不要将从文件中读取的随机数据视为字符串。
  5. 不要进行I / O而不检查返回值。 I / O可能会失败。
  6. ...内存分配也可以。
  7. 使用小型(或小型)固定大小的缓冲区并在循环中读/写可能更好。这样,无论文件大小如何,程序都会使用有限的内存量。

答案 1 :(得分:0)

以下代码:

  1. 仍然有关于未使用的变量argc的警告(请参阅评论)
  2. 缺少检查系统函数调用返回的错误指示的代码
  3. 实际上有效
  4. 现在是代码

    //#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);
    }