gpt4 book ai didi

c - 使用 fgets 读取从 START 到 STOP 字符串的所有文件字符

转载 作者:行者123 更新时间:2023-11-30 16:23:57 25 4
gpt4 key购买 nike

我需要读取 START 和 STOP 字符串之间的整个文件并将该字符串写入新文件。

例如 file1.txt = "Hello START world! STOP"并写入 new file2.txt = "world!"(START 之后和 STOP 之前没有空格)

我已经有了该代码我只能使用 4 个函数:fopen()、fclose()、fgetc()、fputc()

我的代码无法正常工作。它从 START 开始,但最后写入空格 STO 字符。

你能帮我解决这个算法吗?谢谢

#include <stdio.h>

int main( int argc, char *argv[] ) {
FILE *input;
FILE *output;
char c;

char start[] = "START";
char stop[] = "STOP";

int started = 0;
int stopped = 0;

input = fopen(argv[1], "r");
output = fopen(argv[2], "w");

c = fgetc(input);
int i = 0;
while(c != EOF) {
if(started == 0) {
//find start
if(c == ' ' || c == '\n' || c == ',' || c == '.')
i = 0;
else
{
if(c == start[i])
i++;
else
i = 0;
}
if(i == 5) {
started = 1;
i = 0;
c = fgetc(input); //move space
}
} else {
//write letters until stop
if(stopped == 0) {
//find stop
if(c == ' ' || c == '\n' || c == ',' || c == '.')
i = 0;
else
{
if(c == stop[i])
i++;
else
i = 0;
}
if(i == 4) {
stopped = 1;
i = 0;
break;
}
}
if(c != 'S' && c != 'T' && c != 'O' && c != 'P')
fputc(c, output);
}
c = fgetc(input);
}
fclose(input);
fclose(output);

return 0;
}

最佳答案

为了实现您想要的效果,您可以读取整个文件,然后使用 srtok 函数将文本分隔为标记(使用空格字符作为分隔符)。

然后您可以比较每个标记并查找开始和停止条件。

根据您的示例,这应该有所帮助。

引用号:https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

关于c - 使用 fgets 读取从 START 到 STOP 字符串的所有文件字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53771967/

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