我想逐行读取文本文件,执行一些检查,如果不需要该行,请将其删除。 我已经完成了阅读线的代码,但是如果不是我所要求的,我不知道如何删除那一行。 请帮我find最简单的删除线的方法。 这是我的代码片段,我试过了:
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");
这里是一个例子:
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"); }
您可以将不包含数字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" );
另一个解决方案可能是写回相同的文件(回写除了不需要的行之外的内容),并在完成时使用Windows API函数SetEndOfFile
截断它。 这可能会使代码变得有点混乱,但是您不需要创建该文件的第二个副本,因此从磁盘使用的角度来看它更有效率。
解决这个问题有很多,其中之一就是,你可以打开另一个文件来写,当你不想写的时候忽略这个绘画,然后继续写直到文件结束。 稍后,您可以删除旧文件,并使用旧文件重新命名新文件。
if(number == 2) { continue; } else { writetofilefunction() }