加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 从文本文件中读取一行并将其删除

发布时间:2020-12-16 09:43:48 所属栏目:百科 来源:网络整理
导读:我想逐行读取文本文件,执行一些检查,如果不需要行,则删除它. 我已经完成了阅读行的代码,但如果我不需要,我不知道如何删除该行. 请帮我找到删除该行的最简单方法. 这是我尝试的代码片段: char ip[32]; int port; DWORD dwWritten; FILE *fpOriginal,*fpOutpu
我想逐行读取文本文件,执行一些检查,如果不需要行,则删除它.
我已经完成了阅读行的代码,但如果我不需要,我不知道如何删除该行.
请帮我找到删除该行的最简单方法.
这是我尝试的代码片段:

char ip[32];
   int port;
   DWORD dwWritten;
   FILE *fpOriginal,*fpOutput;
   HANDLE hFile,tempFile;
   hFile=CreateFile("Hell.txt",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
   tempFile=CreateFile("temp.txt",0);
   WriteFile(hFile,"10.0.1.25 524192rnrn10.0.1.25 524193rnrn",strlen("10.0.1.25 524192rnrn10.0.1.25 524193rnrn"),&dwWritten,0);
   fpOriginal = fopen("Hell.txt","r+");
   fpOutput = fopen("temp.txt","w+");

   while (fscanf(fpOriginal," %s %d",ip,&port) > 0) 
      {
         printf("nLine1:");
         printf("ip: %s,port: %d",port);
         char portbuff[32],space[]=" ";
         sprintf(portbuff,"%i",port);
         strcat(ip," ");
         strcat(ip,portbuff);
         if(port == 524192)
            printf("n Delete this Line now");
         else
            WriteFile(tempFile,strlen(ip),0);
      }

     fclose(fpOriginal);
     fclose(fpOutput);
     CloseHandle(hFile);
     CloseHandle(tempFile);
     remove("Hell.txt");
     if(!(rename("temp.txt","Bye.txt")))
     {
         printf("ncould not renamen");
     }
     else 
        printf("nRename Donen");
     //remove ("Hell.txt");

解决方法

这是一个例子:

char* inFileName = "test.txt";
char* outFileName = "tmp.txt";
FILE* inFile = fopen(inFileName,"r");
FILE* outFile = fopen(outFileName,"w+");
char line [1024]; // maybe you have to user better value here
int lineCount = 0;

if( inFile == NULL )
{
    printf("Open Error");
}

while( fgets(line,sizeof(line),inFile) != NULL )
{
    if( ( lineCount % 2 ) != 0 )
    {
        fprintf(outFile,"%s",line);
    }

    lineCount++;
}


fclose(inFile);
fclose(outFile);

// possible you have to remove old file here before
if( !rename(inFileName,outFileName) )
{
    printf("Rename Error");
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读