立即註冊 登錄
拉比安羅斯 La Vie En Rose 討論區 返回首頁

linmasaki的個人空間 http://www.shiner96500.com/bbs/?54 [收藏] [複製] [分享] [RSS]

日誌

C顛倒轉換程式

已有 1252 次閱讀2007-8-10 04:32 |個人分類:奇摩知識+及暫存空間用

#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行
}

全部作者的其他最新日誌

評論 (0 個評論)

facelist

您需要登錄後才可以評論 登錄 | 立即註冊

小黑屋|Archiver|La Vie En Rose

GMT+8, 2024-5-7 08:30 , Processed in 0.056435 second(s), 15 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

返回頂部