How do I clear the whole contents of a file in C?
As @stefan said using fopen()
with "w" mode will do the job for you. When you open a file with "w" flag it creates an empty file for writing. If a file with the same name already exists its contents are erased and the file is treated as an empty new file.
If the file is already open you can use freopen()
function from stdio.h with "w" mode as it will first close the file and then reopen it for writing erasing whatever was in the file previously.
C language ~ data file by using delete function modify text file content (File IO)
Try this
int delete_line, temp;
char reply;
printf("Enter file name: ");
scanf("%s", filename);
do{
temp = 1;
....
I hope this helps.
How to remove a word from text file in C program?
This example worked for phrases, I didn't check for larger files or with more content.
#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;
}
}
Clear data inside all files in C++
fstream can't open all files of a directory, instead, you can iterate each file.
This example only works on C++17
#include <string>
#include <iostream>
#include <filesystem>
#include <fstream>
//namespace fs = std::experimental::filesystem; //for visual studio
namespace fs = std:::filesystem;
int main()
{
std::string path = "path_to_directory";
for (auto & p : fs::directory_iterator(path)) {
if (fs::is_regular_file(p)){
std::fstream fstr;
fstr.open(p.path().c_str(), std::ios::out | std::ios::trunc);
//do something
fstr.close()
}
}
}
Older compilers(Windows):
#include <Windows.h>
#include <string>
#include <fstream>
std::wstring path = L"path_to_directory";
path += L"\\*";
WIN32_FIND_DATA data;
HANDLE hFind;
if ((hFind = FindFirstFile(path.c_str(), &data)) != INVALID_HANDLE_VALUE) {
do {
if (data.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
std::fstream fstr;
fstr.open(data.cFileName, std::ios::out | std::ios::trunc);
//do something
fstr.close();
}
} while (FindNextFile(hFind, &data) != 0);
FindClose(hFind);
}
File Handling in C - Removing specific words from a list in text file
- You open two files: the one you've got (for reading) and a new one (for
writing). - You loop through the first file reading each line in turn.
- You compare the contents of each line with the words you need to
delete. - If the line does not match any of the deletion words, then
you write it to the new file.
If the manipulation that you need to do is much more complex then you can literally "read it into memory" using mmap(), but that is a more advanced technique; you need to treat the file as a byte array with no zero terminator and there are lots of ways to mess that up.
How can I delete from a text file?
- You open two files: the one you've got (for reading) and a new one (for writing).
- You loop through the first file reading each line in turn.
- You compare the contents of each line with the words you need to delete.
- If the line does not match any of the deletion words, then you write it to the new file.
Josuel, as taken from my previously answered question by Richard Urwin
You can use the following code:
#include <stdio.h>
int main()
{
FILE *fileptr1, *fileptr2;
char filename[40];
char ch;
int delete_line, temp = 1;
printf("Enter file name: ");
scanf("%s", filename);
//open file in read mode
fileptr1 = fopen("c:\\CTEMP\\Dictionary.txt", "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
//rewind
rewind(fileptr1);
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
fileptr2 = fopen("replica.c", "w");
ch = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);
if (ch == '\n')
{
temp++;
}
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, fileptr2);
}
}
fclose(fileptr1);
fclose(fileptr2);
remove("c:\\CTEMP\\Dictionary.txt");
//rename the file replica.c to original name
rename("replica.c", "c:\\CTEMP\\Dictionary.txt");
printf("\n The contents of file after being modified are as follows:\n");
fileptr1 = fopen("c:\\CTEMP\\Dictionary.txt", "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
fclose(fileptr1);
scanf_s("%d");
return 0;
}
Related Topics
Visual Studio 2013 Error Ms8020 Build Tools V140 Cannot Be Found
Reference to Non-Static Member Function Must Be Called
C++ Bitfield Packing with Bools
What Are Differences Between Std, Tr1 and Boost (As Namespaces And/Or Libraries)
C++ Bool Returns 0 1 Instead of True False
How to Install Tensorflow on Windows
Are There Any Issues with Allocating Memory Within Constructor Initialization Lists
C++ Virtual Function Being Hidden
Two Dimensional Array Using Vector
How to Find the Qt5 Cmake Module on Windows
Is the Std::Set Iteration Order Always Ascending According to the C++ Specification
Why Function Objects Should Be Pass-By-Value
Convert a Number to a String Literal with Constexpr
Command Line Compile Using Cl.Exe
How to Vectorize My Loop with G++