简体   繁体   English

以 C 语言进行反向文件读取的意外 output

[英]Unexpected output for reverse file reading in C language

Here is my code but I don't know why it prints only some part of lines.这是我的代码,但我不知道为什么它只打印部分行。 here is my code:这是我的代码:

#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>

int main(int argc,char *argv[])
{
    FILE *fpr,*fpw;
    int cnt=0;
    fpw=fopen(argv[2],"w+");
    char buff[1000];
    while((fpr=fopen(argv[1],"r"))==NULL)
    {
        printf("\nCan't open file %s\n",argv[1]);
        scanf("re-enter file name:%s\n",argv[1]);
    }
    
    while (!feof(fpr))
    {
        
        fgets(buff,2,fpr);

        if(buff[0]=='\n')
        {
            putc(buff[0],fpw);
            fseek(fpw,0,SEEK_SET);
        
        }
        fputs(buff,fpw);
        cnt++;
    }

    
    fclose(fpr);
    fclose(fpw);
    
}

INPUT FILE:输入文件:

Hrey yhis will print twicw Hrey yhis 将打印两次

lets print thrice让我们打印三次

@why not @为什么不

OUTPUT FILE OUTPUT 文件

lets print thrice @why not让我们打印三次@why not

So.. basically what I was trying to do is actually impossible using lseek/fseek.所以.. 基本上我试图做的事情实际上是不可能使用 lseek/fseek 的。 So I found another approach, as shown in the code below:于是我找到了另一种方法,如下代码所示:

#include <stdio.h> 
#include <string.h> 
#include<stdlib.h>

int main(int argc,char *argv[])
{

    FILE* fr;
    FILE* fw;
    int l=0;
    char lines[10000][100];
    if( ( (fr=fopen(argv[1],"r+"))==NULL || (fw=fopen(argv[2],"w+"))==NULL )  )
    {
        printf("Error reading or opening files %s,%s",argv[1],argv[2]);
    }

    while(fgets(lines[l++], sizeof(lines[l]), fr)!=NULL);
        

    while(l>=0)
        fputs(lines[l--],fw);
        

    fclose(fr);
    fclose(fw);
}

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

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