从文本文件中读取一行并删除它

时间:2013-04-02 07:40:28

标签: c windows file winapi

我想逐行阅读文本文件,执行一些检查,如果不需要该行,请将其删除。 我已经完成了阅读行的代码,但如果我不需要,我不知道如何删除该行。 请帮我找到删除该行的最简单方法。 这是我尝试的代码片段:

   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,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
   tempFile=CreateFile("temp.txt",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
   WriteFile(hFile,"10.0.1.25 524192\r\n\r\n10.0.1.25 524193\r\n\r\n",strlen("10.0.1.25 524192\r\n\r\n10.0.1.25 524193\r\n\r\n"),&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", ip, 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,ip,strlen(ip),&dwWritten,0);
      }

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

4 个答案:

答案 0 :(得分:2)

这是一个例子:

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");
}

答案 1 :(得分:2)

有许多解决这个问题的其中之一就是,你可以打开另一个文件进行写作,当你到达一个你不想写的省略画画并继续写作直到文件结尾。您可以删除旧文件并使用旧文件重命名新文件。

if(number == 2)
{
     continue;
}
else
{
    writetofilefunction()
}

答案 2 :(得分:2)

您可以将所有不包含数字2的行复制到新文件中,然后使用新文件代替旧文件

fp = fopen("File.txt", "r");
fp2 = fopen("File_copy.txt", "w");
while (fscanf(fp, " %s %d", string, &number) > 0) {
        if(number != 2)
        {
             fprintf(fp2, "%s %d\n", string, number);
        }
}
close(fp);
close(fp2);
remove("File.txt");
rename( "File_copy.txt", "File.txt" );

答案 3 :(得分:1)

另一个解决方案可能是回写到同一个文件(写回你读出的内容除了你不想要的行),并在完成时使用Windows API函数SetEndOfFile截断它。代码可能会有些麻烦,但您不需要创建文件的第二个副本,因此从磁盘使用的角度来看它更有效。