gpt4 book ai didi

c - 如何从 C 中的文本文件中删除特定行?

转载 作者:太空狗 更新时间:2023-10-29 15:00:39 25 4
gpt4 key购买 nike

例子:

George 50 40
Lime 30 20
Karen 10 60

do {
printf("\nInput player name:[1..10] ");
fgets(name,10,stdin);
}

输入名称:石灰

那么文本文件将是:

George 50 40
Karen 10 60

最佳答案

有几种方法可以删除一行,一种简单的方法是打开两个文件,一进一出。

然后逐行复制并跳过要删除的行完成后,删除旧文件并将新文件重命名为旧名称。

fopen()
fgets()
fputs()
rename()
unlink()

编辑:上述解决方案适用于小文件,但根据评论,它不适用于大文件,因此这里有一个替代解决方案 (GCC C99),它读取整个文件,找到名称,然后移动该行之后的行在缓冲区中转发。

#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdbool.h>

static size_t deleteLine( char*, size_t, const char* );

int main(int argc, char* argv[])
{
char file[] = "yourfile.txt";

if ( --argc )
{
struct stat st;
if ( stat( file, &st ) != -1 )
{
// open the file in binary format
FILE* fp = fopen( file, "rb" );
if ( fp != NULL )
{
// allocate memory to hold file
char* buffer = malloc( st.st_size );

// read the file into a buffer
if ( fread(buffer, 1, st.st_size, fp) == st.st_size)
{
fclose(fp);

size_t newSize = deleteLine( buffer, st.st_size, argv[1] );

fp = fopen( file, "wb" );
if ( fp != NULL )
{
fwrite(buffer, 1, newSize, fp);
fclose(fp);
}
else
{
perror(file);
}
}
free(buffer);
}
else
{
perror(file);
}
}
else
{
printf( "did not find %s", file );
}
}
return 0;
}

static size_t deleteLine( char* buffer, size_t size, const char* playerName )
{
// file format assumed to be as specified in the question i.e. name{space}somevalue{space}someothervalue\n
// find playerName
char* p = buffer;
bool done = false;
size_t len = strlen(playerName);
size_t newSize = 0;
do
{
char* q = strchr( p, *playerName ); // look for first letter in playerName
if ( q != NULL )
{
if ( strncmp( q, playerName, len ) == 0 ) // found name?
{
size_t lineSize = 1; // include \n already in line size

// count number of characters the line has.
for ( char* line = q; *line != '\n'; ++line)
{
++lineSize;
}

// calculate length left after line by subtracting offsets
size_t restSize = (size_t)((buffer + size) - (q + lineSize));

// move block with next line forward
memmove( q, q + lineSize, restSize );

// calculate new size
newSize = size - lineSize;
done = true;
}
else
{
p = q + 1; // continue search
}
}
else
{
puts( "no such name" );
done = true;
}
}
while (!done);

return newSize;
}

关于c - 如何从 C 中的文本文件中删除特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20716785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com