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

标签 c linux file buffer

//编辑:我将第一个句柄的标志设置为 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”是空的,我不知道为什么。有任何想法吗?

最佳答案

这里有一些评论要点:

  1. Don't cast the return value of malloc() in C .
  2. 不要在堆指针上使用 sizeof,认为它会返回与分配的缓冲区大小有关的任何内容;它不会。您将获得指针的大小。
  3. 使用正确的类型,而不仅仅是 int 用于所有内容。类型很重要,并非所有类型都像 int
  4. 不要将从文件中读取的随机数据视为字符串。
  5. 不做 I/O 也不检查返回值。 I/O 可能会失败。
  6. ...内存分配也是如此。

最好使用一个小的(或更小的)固定大小的缓冲区,并在循环中读/写。这样,无论文件大小如何,您的程序都会使用有限的内存。

关于c - (C Linux) 中的 read() 和缓冲区大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466751/

相关文章:

c - 多线程C程序中串口的调度和访问控制

c - 将 C 变量的值赋给 bash 变量

无法链接 sctp 二进制文件

linux - 获取内核中套接字事件的通知

linux - 从文本文件转换数字

c++ - 从 SYSTEMTIME 到 time_t 的转换给出 UTC/GMT 时间

file - 去。将 []byte 写入文件导致零字节文件

android - 在 Parse.com 获取图像文件的链接

file - Node js将文件发布到远程服务器上的php api

c - 预处理 token : '- -' vs. '--'