#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void Input_file_name(char* , char*) ;
FILE *Open_sourse_file(char*) ;
FILE *Open_destination_file(char*) ;
void Transform_file(FILE* , FILE* , int , int) ;
main(void)
{
FILE *file1 , *file2 ;
char s_name[50] , d_name[50] ;
int f_size ;
int line ;
Input_file_name(s_name , d_name) ;
file1 = Open_sourse_file(s_name) ;
file2 = Open_destination_file(d_name) ;
f_size = File_size(file1) ;
line = File_line(file1) ;
fseek(file1,0,SEEK_SET) ; //將檔案指到開頭的位置
Transform_file(file1,file2,line,f_size) ;
fclose(file1) ;
fclose(file2) ;
}
void Input_file_name(s_name , d_name) //輸入一個要開啟的檔案名稱及目的檔名稱
char *s_name , *d_name ;
{
printf("Please input the SOURCE file name:") ;
scanf("%s",s_name) ;
printf("Please input the DESTINATION file name:") ;
scanf(" %s",d_name) ;
}
FILE *Open_sourse_file(s_name) //開啟一個已存在的檔案
char *s_name;
{
FILE *file1;
file1=fopen(s_name,"r"); /*open source file*/
if (file1==NULL)
{
puts("Cannot open source_file\n");
exit(1);
}
return(file1);
}
FILE *Open_destination_file(d_name) //創造一個新檔案或覆寫原有的檔案
char *d_name;
{
FILE *file2;
file2=fopen(d_name,"w");/*make new file*/
if (file2==NULL)
{ puts("Cannot open destination_file\n");
exit(1);
}
return(file2);
}
int File_size(file1) //計算檔案的大小
FILE *file1 ;
{
int f_size ;
fseek(file1,0,SEEK_END) ; //將檔案指到最後
f_size = ftell(file1) ;
fseek(file1,0,SEEK_SET) ; //將檔案指到開頭的位置
return(f_size) ;
}
int File_line(file1) //計算有幾行
FILE *file1 ;
{
char ch ;
int line = 0 ;
while((ch=fgetc(file1)) != EOF ) //EOF為最後一行
{
if(ch == '\n') //每有一個\n就代表多一行
{
line++ ;
}
}
return(line) ;
}
void Transform_file(file1,file2,line,f_size) /*開始進行顛倒原始檔的轉換*/
FILE *file1 , *file2 ;
int line , f_size ;
{
int ch , ch_n ; //字元元素
int sp ; //多餘的陣列元素
int n_line = 0 ; /*用來分開每一行的變數,為原始檔案的第n_line+1行*/
int j ;
char tra_file[line][f_size] ;
while((ch=fgetc(file1)) != EOF )
{
tra_file[n_line][ch_n] = ch ;
if(ch == '\n') //遇到跳行則儲存一行起來
{
for(sp = ++ch_n ; sp<f_size ; sp++)
tra_file[n_line][sp] = '\0' ; //多餘的陣列元素補上'0'
n_line++ ;
ch_n = 0 ;
}
else
ch_n++ ;
}
for(j=1 ; j<=line ; j++)
fputs(tra_file[line-j] , file2) ; //(總行數-j)為倒數第j行
}