1. 程式人生 > >C讀寫檔案--刪除指定的一行

C讀寫檔案--刪除指定的一行

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

void InsertLine(char* FileName, int Line, char str[256]);
void deleteLine(char* FileName, int lineno)   ;
void print(char *filepath);

int  main()  
{  
   print("test.txt");  
   printf("/n....................................................../n");

   InsertLine("test.txt", 3, "1111111111/n");  
   print("test.txt");  
  
   printf("/n....................................................../n");  
   deleteLine("test.txt", 3);  
   printf("/n....................................................../n");  
   print("test.txt");  
   return   0;  

/**********************************************************************
* 函式名稱: InsertLine
* 功能描述: 向檔案指定行增加一行
* 訪問的表: 無
* 修改的表: 無
* 輸入引數: char* FileName 檔案
    int Line       行;
*     char str[256]  要增加的內容
*
***********************************************************************/
void InsertLine(char* FileName, int Line, char str[256])  
{  
   int   Lid=0;  
   int   MaxLine=0;  
   FILE*   fp=NULL;  
   char   Buf[256]="";  
   char   tmp[50][256]={0};  

   
   if ((fp=fopen(FileName,"r+")) == NULL)  
   {  
   printf("Can't   open   file!/n");  
   return;  
   }  
   while (fgets(Buf, 256 ,fp))  
   {  
   Lid++;  
   if(Lid == Line)
   {
    strcpy(tmp[Lid++],str);
   }
   strcpy(tmp[Lid],Buf);  
   } 

 MaxLine=Lid;  
 rewind(fp);  
 for(Lid=1 ;Lid <= MaxLine;Lid++)
 {
  fputs(tmp[Lid],fp);
 }

 fclose(fp);  

/**********************************************************************
* 函式名稱: InsertLine
* 功能描述: 向檔案指定行增加一行
* 訪問的表: 無
* 修改的表: 無
* 輸入引數: char* FileName 檔案
    int Line       行;
*     char str[256]  要增加的內容
*
***********************************************************************/
void deleteLine(char* FileName, int lineno)  
{  
   int   Lid=0;  
   int   MaxLine=0;  
   FILE*   fp=NULL;  
   char   Buf[256]="";  
   char   tmp[20][256]={0};  
   char   *p   =   Buf;    
   
      if ((fp = fopen(FileName, "r+")) == NULL)  
   {  
    printf("Can't   open   file!/n");  
    return;  
   } 

   while ((p = fgets(Buf, 256, fp)) != NULL)  
   {  
     Lid++;  
     if (Lid == lineno)  
     {  
      if ((p = fgets(Buf, 256, fp)) != NULL) 
      {  
      strcpy(tmp[Lid], Buf);  
     }  
      }  
    else  
    {
      strcpy(tmp[Lid], Buf);
     }
   } 

   MaxLine = Lid;  
   rewind(fp);  
   fclose(fp);    
   remove(FileName);   //   刪除原檔案  

   if((fp = fopen(FileName, "w")) == NULL)  
   {  
     printf("Can't   open   file!/n");  
     return;  
   }

    for(Lid = 1; Lid <= MaxLine; Lid++)  
    {
    fputs(tmp[Lid], fp);  
    }
    fclose(fp);  
}  
   
//輸出到控制檯   
void print(char *filepath)  
{  
    int  nl = 0;  
    FILE  *stream;  
    char  s[256];  
    char  *p   =   s;    
   
    stream = fopen(filepath, "r+");  
    while ((p = fgets(s, 256, stream)) != NULL)  
    {  
            nl++;  
      printf("Line  %d:  %s", nl, s);  
     }  
   
     fclose(stream);                
}