簡體   English   中英

使用fgets從START到STOP字符串讀取所有文件字符

[英]Read all file chars using fgets from START to STOP string

我需要讀取START和STOP字符串之間的整個文件,並將該字符串寫入新文件。

例如,file1.txt =“ Hello START world!STOP”並寫入新的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM