c - 在C中滚动文本文件

标签 c text-files fgetc

我在 C 语言方面遇到问题。我必须找到并打印输入文本文件到输出文本文件中单词 STARTSTOP 之间的每隔一个单词。我创建了一个函数,它控制文本文件 STOP 中是否是下一个单词。但是如果在输入文本文件单词 STOP 中,函数 fgetc 移动到 T 并检查,下一个字母不是 O 并中断...但我需要在单词之前获取停止。我怎样才能做到这一点?除了 fgetcfputcfopenfclose 之外,我无法使用任何库函数。

这里是代码:

int search_STOP(int ch, FILE* in) { if(ch == 'S'){
  ch = fgetc(in);
  if(ch =='T'){
    ch = fgetc(in);
    if(ch == 'O'){       
       ch = fgetc(in);
       if(ch == 'P'){       
             return 1;
       }
    }
  }
  return 0;
}

最佳答案

我曾经遇到过同样的问题。大多数问题都可以通过谷歌搜索并将代码片段拼接在一起来解决。

为了您的目的,我稍微更改了当时编写的代码(因为我正在执行的工作比仅仅忽略搜索词中的大小写稍微复杂一些)。请注意,在这段代码中以小写形式提供搜索词(“start”)非常重要。您可以更改它,以便它也采用大写搜索词,但我会将其留给您自己解决。

#include <stdio.h>
#include <stdlib.h>

int specialFind(char *buffer, const char *s, int startIndex, int endIndex);

int specialFind(char *buffer, const char *s, int startIndex, int endIndex)
{
    int findIndex = 0;

    int s_len = 0;
    int signComp = 0;

    while(s[s_len] != '\0')
    {
        s_len++;
    }

    char msg[64];

    for(int i = startIndex; i < endIndex; i++)
    {
        if(buffer[i] >= 65 && buffer[i] <= 90)
        {
            signComp = 32;
        }
        else
        {
            signComp = 0;
        }
        if(buffer[i] + signComp == s[findIndex])
        {
            findIndex++;
        }
        else
        {
            findIndex = 0;
        }
        if(findIndex == s_len)
        {
            return i - s_len + 1;
        }
    }
    return -1;
}

int main()
{
    FILE *fileptr;

    //  First opening and reading to determine file size
    fileptr = fopen("textfile.txt", "r");
    int filelen = 0;
    char c;
    while(1)
    {
        c = fgetc(fileptr);
        filelen++;
        if(feof(fileptr))
        {
            break;
        }
    }
    fclose(fileptr);

    //  Now we're actually gonna read the file to the buffer
    char buffer[filelen];
    fileptr = fopen("textfile.txt", "r");
    int index = 0;
    while(1)
    {
        buffer[index] = fgetc(fileptr);
        index++;
        if(feof(fileptr))
        {
            break;
        }
    }
    fclose(fileptr);

    return 1;
}

关于c - 在C中滚动文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175208/

相关文章:

c - 什么更好 : Select vs Threads?

java - 为什么我的代码不写入文本文件?

C-从文件中读取

c - 使用 OpenMP 并行化 if else 语句

C中的Python union(), difference()方法

c - 将指针数组分配给字符串

python - 从txt文件Python创建字典

c# - 逐行读取文本文件的最快方法是什么?

c - 为什么这个程序的行为类似于 `tail -f`

c - C 标准和 C POSIX 中的 IO