4

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

   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

4 回答 4

4

这是一个例子:

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");
}
于 2013-04-02T08:02:03.363 回答
1

有很多方法可以解决这个问题,其中一个是,当您到达不想写入的点时,您可以打开另一个文件进行写入,忽略该绘画并继续写入直到文件结束。稍后您可以删除旧文件并用旧文件重命名新文件。

if(number == 2)
{
     continue;
}
else
{
    writetofilefunction()
}
于 2013-04-02T08:03:09.170 回答
1

您可以将所有不包含数字 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" );
于 2013-04-02T08:45:05.993 回答
1

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

于 2013-04-02T09:53:24.223 回答