繁体   English   中英

从文件到文件的读写,直到linux下的c中的EOF

[英]read and write from file to file until EOF in c under linux

我有这个代码在c中打开文件并将其内容写入另一个文件,但是当我运行它错误的结果和一些行只复制并进入无限循环:

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>


//static int    read_cnt;
//static char   *read_ptr;
//static char   read_buf[1024];


int main(int argc, char **argv)
{
    //i have a variable size which is an int and is the byte size of the file
    //i got the byte size of file from stat
    int fileread = open("/tmp/des.py",'r');
    char buffer[1024];



    while((fileread = read(fileread, buffer, sizeof(buffer))>0));
    {
        if(fileread < 0) 
              printf("error write");
    }


    int filewrite = open("/tmp/original.txt", O_WRONLY|O_CREAT);

    while ((filewrite = write(filewrite, buffer, sizeof(buffer))>0))
    {
        if(filewrite < 0)
              printf("error write");
    }


    close(filewrite);
    close(fileread);

    return 0;
}

那么如何解决这个问题呢

在这个声明中

    while(   (fileread=read(fileread,buffer,sizeof(buffer))>0));

你用读取的字节数覆盖fileread的值,这是一个文件句柄。 代码应该是

    int bytesRead = 0;
    while(   (bytesRead=read(fileread,buffer,sizeof(buffer))>0));

写部分也是一样的

OP尝试复制整个内容,但有2个不相交的while循环。 第一个将所有数据读入同一个小缓冲区。 然后缓冲区的最后一些内容用于无休止地写入该缓冲区。

只需要1个while循环 写缓冲区需要使用读取的数据长度,而不是sizeof buffer

int fileread = open("/tmp/des.py", O_RDONLY);
int filewrite = open("/tmp/original.txt", O_WRONLY|O_CREAT);
// After successfully opening ...
char buffer[1024];
ssize_t inlen;
ssize_t outlen;
while((inlen = read(fileread, buffer, sizeof buffer)) > 0) {
  outlen = write(filewrite, buffer, inlen);  // Note use of inlen
  if (inlen != outlen) {
    handle_error();
  }
}
if (inlen < 0) {
  handle_error();
}
close(filewrite);
close(fileread);

你需要

size_t bytesRead = 0;
while((bytesRead=read(fileread,buffer,sizeof(buffer))>0));

你需要这个,因为read返回了多少个符号被读取,所以在你的情况下你只是覆盖了文件句柄。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM