如何从 C 程序中的文本文件中删除一个单词?
How to remove a word from text file in C program?
所以我有一个名为 test.txt 的文件,其中包含以下文本:
Hello World! I hope you are doing well. I am also well. Bye see you!
现在我想从文本文件中删除 Bye 一词。我想在 test.txt 文件中而不是单独的文件中对同一个文件进行更改。我如何在 C 程序中执行此操作?
提前致谢
这个例子适用于短语,我没有检查更大的文件或更多的内容。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void remove_word(char * text, char * word);
int main()
{
char * filename = "test.txt";
char * text = (char*)malloc(sizeof(char) * 100);
char * wordToRemove = (char*)malloc(sizeof(char) * 20);
// Word to remove
strcpy(wordToRemove, "Bye");
// Open for both reading and writing in binary mode - if exists overwritten
FILE *fp = fopen(filename, "wb+");
if (fp == NULL) {
printf("Error opening the file %s", filename);
return -1;
}
// Read the file
fread(text, sizeof(char), 100, fp);
printf ("Readed text: '%s'\n", text);
// Call the function to remove the word
remove_word(text, wordToRemove);
printf ("New text: '%s'\n", text);
// Write the new text
fprintf(fp, text);
fclose(fp);
return 0;
}
void remove_word(char * text, char * word)
{
int sizeText = strlen(text);
int sizeWord = strlen(word);
// Pointer to beginning of the word
char * ptr = strstr(text, word);
if(ptr)
{
//The position of the original text
int pos = (ptr - text);
// Increment the pointer to go in the end of the word to remove
ptr = ptr + sizeWord;
// Search in the phrase and copy char per char
int i;
for(i = 0; i < strlen(ptr); i++)
{
text[pos + i] = ptr[i];
}
// Set the "new end" of the text
text[pos + i] = 0x00;
}
}
所以我有一个名为 test.txt 的文件,其中包含以下文本:
Hello World! I hope you are doing well. I am also well. Bye see you!
现在我想从文本文件中删除 Bye 一词。我想在 test.txt 文件中而不是单独的文件中对同一个文件进行更改。我如何在 C 程序中执行此操作?
提前致谢
这个例子适用于短语,我没有检查更大的文件或更多的内容。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void remove_word(char * text, char * word);
int main()
{
char * filename = "test.txt";
char * text = (char*)malloc(sizeof(char) * 100);
char * wordToRemove = (char*)malloc(sizeof(char) * 20);
// Word to remove
strcpy(wordToRemove, "Bye");
// Open for both reading and writing in binary mode - if exists overwritten
FILE *fp = fopen(filename, "wb+");
if (fp == NULL) {
printf("Error opening the file %s", filename);
return -1;
}
// Read the file
fread(text, sizeof(char), 100, fp);
printf ("Readed text: '%s'\n", text);
// Call the function to remove the word
remove_word(text, wordToRemove);
printf ("New text: '%s'\n", text);
// Write the new text
fprintf(fp, text);
fclose(fp);
return 0;
}
void remove_word(char * text, char * word)
{
int sizeText = strlen(text);
int sizeWord = strlen(word);
// Pointer to beginning of the word
char * ptr = strstr(text, word);
if(ptr)
{
//The position of the original text
int pos = (ptr - text);
// Increment the pointer to go in the end of the word to remove
ptr = ptr + sizeWord;
// Search in the phrase and copy char per char
int i;
for(i = 0; i < strlen(ptr); i++)
{
text[pos + i] = ptr[i];
}
// Set the "new end" of the text
text[pos + i] = 0x00;
}
}