2013-12-24 124 views
2

我有下面的代碼,我想寫逆向一個文件的內容複製到另一個文件複製逆向一個文件的內容複製到另一個文件

# include <stdio.h> 
# include <conio.h> 
# include <process.h> 

void main() 
{ 
    FILE *f1,*f2; 
    char file1[20],file2[20]; 
    char ch; 
    int n; 
    printf("Enter the file1 name:"); 
    scanf("%s",file1); 
    printf("Enter the file2 name:"); 
    scanf("%s",file2); 
    f1=fopen(file1,"r"); 
    f2=fopen(file2,"w"); 
    if(f1==NULL || f2==NULL) 
    { 
     printf("Cannot open file"); 
     exit(1); 
    } 
    printf("Characters to read from end of file :"); 
    scanf("%d",&n); 
    fseek(f1,-n,SEEK_SET); 
    while(!feof(f1)) 
    { 
     ch=fgetc(f1); 
     fputc(ch,f2); 
    } 
    fcloseall(); 
    getche(); 

但執行後,內容不會被反寫訂單,但它被複制,因爲它是,我已經使用

fseek(f1,-n,SEEK_SET). 

我不知道我哪裏錯了。

回答

2

確定的file1長度:中file1file2

fseek(file1, 0, SEEK_END); 
int file1Length = ftell(file1); 

寫的內容,在反向:

for(int filePos = file1Length; filePos >= 0; filePos--) 
{ 
    fseek(file1, filePos, SEEK_SET); 
    fputc(fgetc(file1), file2); 
} 
+0

謝謝小提琴比特:) – user3027039

+0

@ user3027039任何時候。 –

2

fgetc在循環工作向前。要反向讀取,您需要在循環中額外添加fseek(f1, -2, SEEK_SET)

您需要-2,因爲您需要重新回顧剛剛閱讀的單個字符,然後再回到另一個位置以便在此之前訪問該字符。

我不認爲你需要的線

fseek(f1,-n,SEEK_SET); 

在所有 - 你需要從閱讀你的文件的末尾。這將文件指針定位到要寫入的最後一個字符的正確位置(反向)。你想

fseek(f1,0,SEEK_END); 

(然後你必須考慮我上面說的)。

如果您只需將所需數量的字符讀入臨時緩衝區並將其寫入反向,則該任務將更加容易。

+0

謝謝Jongware :) – user3027039

+0

@ user3027039:不客氣。您的狀態表明您尚未閱讀[關於](http://stackoverflow.com/about)頁面。特此邀請您這樣做。另外,請閱讀[有人回答我的問題,該怎麼做!](http://meta.stackoverflow.com/help/someone-answers)。 – usr2564301

0

下面的程序在控制檯上以相反的順序打印文件。您可以將其寫入另一個文件,而不是控制檯。

#include <stdio.h> 
#include <errno.h> 
int main(void) 
{ 
    char c; 
    FILE *ifp, *fp2; 
    char *fileName="a.txt"; 
    ifp= fopen(fileName, "rb");/* binary mode for ms-dos */ 
    fseek(ifp,0L, SEEK_END);/* move to end of the file */ 
    fseek(ifp,-1L, SEEK_CUR);/* back up one character */ 
    do 
    { 
     c = fgetc(ifp);/* move ahead one character*/ 
     putchar(c); 
     fseek(ifp,-2L, SEEK_CUR);/* back up twocharacters*/ 
    } while (ftell(ifp)>0); 
    c = fgetc(ifp);/* move ahead one character*/ 
    putchar(c); 
    fclose(ifp); 
    getch(); 
    return 0; 
} 
相關問題