Linux下文件操作,打开一个文件并修改文件后5个字符为abcde

来源:互联网 发布:爱国治民能无知乎 编辑:程序博客网 时间:2024/06/06 10:52

编写一个小程序,实现如下功能:

l  打开一个文本文件(纯ascii码构成,字符个数大于5)

l  输出文件的总行数

l  通过写文件操作将此文件的最后5个字符替换为“abcde”

 

#include <stdio.h>

#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <ucontext.h>

#define BUF_LEN 128    /*缓冲区长度*/
#define REPLACE_STR "abcde"   /*替换的字符串*/

int main(int argc, char *argv[])
{
      FILE *fp ;           
      char buf[BUF_LEN]={0}; 
      char bufTemp[BUF_LEN]={0}; 
      char modifyBuf[BUF_LEN]=REPLACE_STR;
      int lineCnt = 0;   /*文件行数初始化为0*/
      int writeFlag=0;   /*文件写标志位初始值为0*/
      int sumstrLength=0; 
 
      fp= fopen("homework.txt", "r+");   /*以读写方式打开文件*/ 
      if(NULL==fp) 
        {
        fprintf(stderr,"failed open the file\n");   /*提示打开文件失败*/
        return -1; 
        }
else
{
          while (fgets(buf, BUF_LEN, fp))   /*fgets循环读取,直到文件最后,才会返回NULL*/  
             {
            lineCnt++;   /*统计文件行数*/ 
            sumstrLength+=strlen(buf); 
             }
         printf("lineCnt= %d\n\n", lineCnt);     /*打印总行数*/
 
         if((sumstrLength>=5) && (0==strcmp(modifyBuf,"abcde")) && (0==writeFlag))  /*文本内容长度大于5,写入的内容为abcde,且未执行过写操作,执行替换操作*/  
            {
            fseek(fp, -(strlen(modifyBuf)+1), SEEK_END); /*移动文件指针到待写入的位置*/         
            fprintf(fp, "%s", modifyBuf);      /*写入数据*/ 
            writeFlag=1; 
            fprintf(stdout,"Have replaced successfully!\n\n");
             }
         else
            {
if(sumstrLength<5) 
{
           fprintf(stderr,"The length of content is less 5!!\n\n");  /*内容长度小于5时,给出错误提示*/
}
else
{
;
}
            if(0!=strcmp(modifyBuf,"abcde")) 
{
          fprintf(stderr,"The replacing string is not the abcde!!\n\n");/*替换的字符串不是abcde时,给出错误提示*/
}
else
{
;
}

if(1==writeFlag) 
{
          fprintf(stderr,"The file can be modified only only one time!!\n\n");/*写操作次数大于1时给出错误提示*/
}
else
{
;
}
  }
        fclose(fp); 
       }
    
    return 0;
}