C/C++

Как удалять элементы из файла?

Есть файл, в нем некоторый текст. Необходимо удалить из этого текста определенные слова. Какими методами для этого использовать, не перезаписывая "подходящие" слова во второй файл?
Dmitry H
Dmitry H
82
Этот код считывает все содержимое файла в буфер в памяти, заменяет слова, которые мы хотим удалить, пустой строкой, а затем записывает измененный текст обратно в исходный файл. Таким образом, вы можете удалить определенные слова из текста, не используя второй файл.
 #include  
#include
#include

int main(void) {
// Open the file for reading and writing
FILE* file = fopen("file.txt", "r+");

// The words that we want to remove from the text
const char* words_to_remove[] = {"word1", "word2", "word3"};

// Determine the size of the file
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
rewind(file);

// Allocate a buffer to hold the contents of the file
char* buffer = malloc(file_size + 1);
if (buffer == NULL) {
fprintf(stderr, "Error: unable to allocate buffer\n");
return 1;
}

// Read the entire file into the buffer
fread(buffer, file_size, 1, file);
buffer[file_size] = '\0';

// Replace the words that we want to remove with an empty string
for (int i = 0; i < sizeof(words_to_remove) / sizeof(words_to_remove[0]); i++) {
char* word_ptr = buffer;
while ((word_ptr = strstr(word_ptr, words_to_remove[i])) != NULL) {
memset(word_ptr, ' ', strlen(words_to_remove[i]));
word_ptr += strlen(words_to_remove[i]);
}
}

// Write the modified text back to the file
rewind(file);
fwrite(buffer, file_size, 1, file);

// Clean up
free(buffer);
fclose(file);

return 0;
}
Этот код читает файл построчно и заменяет слова, которые мы хотим удалить, пустой строкой. Затем он записывает измененную строку обратно в файл. Таким образом, вы можете удалить определенные слова из текста, не считывая сразу весь файл в память.
 #include  
#include
#include

int main(void) {
// Open the file for reading and writing
FILE* file = fopen("file.txt", "r+");

// The words that we want to remove from the text
const char* words_to_remove[] = {"word1", "word2", "word3"};

// Read the file line by line
char line[1024];
while (fgets(line, sizeof(line), file) != NULL) {
// Replace the words that we want to remove with an empty string
for (int i = 0; i < sizeof(words_to_remove) / sizeof(words_to_remove[0]); i++) {
char* word_ptr = line;
while ((word_ptr = strstr(word_ptr, words_to_remove[i])) != NULL) {
memset(word_ptr, '', strlen(words_to_remove[i]));
word_ptr += strlen(words_to_remove[i]);
}
}

// Write the modified line back to the file
fseek(file, -strlen(line), SEEK_CUR);
fputs(line, file);
}

// Close the file
fclose(file);

return 0;
}
XU
Xanuman Uadjit
2 589
Лучший ответ
Dmitry H Спасибо большое!! Синтаксис немного не моего уровня, но попробую разобраться что и как работает
удалять в редакторе текста
BG
B!rd Gg
42 631
Ctrl + f(4)
Толик Танков Я не чурка я англичанка к сожалению отец армянин но хоть мать испанка

Похожие вопросы