c - 将用户输入与文件中的文本进行比较
问题描述
下面的代码可以输出我文件中的内容。我试图找到一种方法来比较用户输入的单词/字符是否包含在文本文件中。例如,如果用户写“r”,那么程序会在文件中找到所有带有“r”的单词并输出它们。在那之后,我想用一些东西替换这个词,所以不是“r”,而是“k”。例如,“roadtrip”-->“koadtrip”。
#define MAX 1024
int main() {
FILE* myFile = fopen("C:\\Users\\Luther\\Desktop\\txtfiles\\words.txt", "r+");
char inputWord[MAX];
char lineBuffer[MAX];
if (myFile1 == NULL)
{
printf("File Does Not Exist \n");
return 1;
}
printf("Enter the word \n");
fgets(inputWord, MAX, stdin);
while (!feof(myFile1))
{
char lineBuffer[1024];
fscanf(myFile1, "%1024[^\n]\n", lineBuffer);
//printf("%s\n", lineBuffer);
while (fgets(lineBuffer, MAX, myFile)) {
if (strstr(lineBuffer, inputWord))
puts(lineBuffer);
}
}
}
我已经设法让它工作,现在程序输出有关用户输入的信息。如果在文本文件中找到相同的单词或其中的一部分,则打印该单词。看下面的截图:
现在我正在寻找一种方法来替换这个词。例如,在这种特定情况下,用户输入的单词是“es”,然后打印所有包含“es”的单词。有没有一种方法可以在所有情况下替换“es”并使其变为“er”。然后将更改保存在另一个文件中,而不更改原始文件中的任何内容。
解决方案
其他一些起点
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<regex.h>
#include<sys/types.h>
int main (){
//open file
FILE *file_pointer = fopen("./test_txt.txt", "r");
const char* search_for = "3_hau_gbs";
int line_number = 1;
char* line = NULL;
size_t len = 0;
regex_t regex;
int failed = regcomp(®ex, search_for, REG_EXTENDED);
//You are serching bitwise, so you must first semicompile it
if(failed){
regfree(®ex);
} else {
while(getline(&line, &len, file_pointer) != -1){
//go line after line and check if it include the word you
//you are looking for
int match = regexec(®ex, line, 0, NULL, 0);
if(!match){
//when find so output
printf("%d:%s",line_number, line);
}
line_number++;
}
if(line){
free(line);
}
regfree(®ex);
fclose(file_pointer);
}
}
推荐阅读
- javascript - 有没有办法在 Google App Script 中使用 python 函数?
- c# - 为什么图表不更新
- abp - 如何在 ABP 框架中禁用事务?
- docusignapi - 基于模板将文档添加到信封
- javascript - 使用 jQuery ajax 和 Django 上传文件
- c# - 如何修复数学随机方法组浮动
- javascript - 如何创建创建新 html 文件的函数/方法?
- javascript - 如何使用 Vuejs 中的链接重定向到另一个组件?
- python - 使用 python (tabula) 将 PDF 导出为 csv
- java - 需要帮助使用带括号和 OR 操作的正则表达式