簡體   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