且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

读取文本文件中的行并将其删除

更新时间:2023-01-30 19:32:46

下面是一个例子:

 的char * inFileName =的test.txt;
char *之outFileName =tmp.txt;
FILE * INFILE = FOPEN(inFileName,R);
FILE *不过outFile = FOPEN(outFileName,W +);
焦线[1024]; //也许你有用户更好的价值在这里
INT lineCount = 0;如果(INFILE == NULL)
{
    的printf(打开错误);
}而(与fgets(线,的sizeof(线),INFILE)!= NULL)
{
    如果((lineCount%2)!= 0)
    {
        fprintf中(不过outFile,%S,行);
    }    lineCount ++;
}
FCLOSE(INFILE);
FCLOSE(不过outFile);//可能你之前在这里删除旧文件
如果(!重命名(inFileName,outFileName))
{
    的printf(重命名错误);
}

I want to read a text file line by line, perform some checks, and if the line is not required, delete it. I have done the code for reading line, but I don't know how to delete that line if it is not required by me. Please help me find the simplest method for deleting the line. Here is my code snippet what I tried:

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

here's an example:

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