Question:
C programming: How do I delete contents of a text file?
/sci/borg
2010-03-20 02:45:02 UTC
All the guides I'm finding are for appending and reading but no deleting. :(
Three answers:
MichaelInScarborough
2010-03-20 07:31:57 UTC
I assume that you don't want to delete the whole content of the text file, but just part of it.These snippets are simplified.



file.txt contains: "Hello World, here here I am!";



FILE *fp = fopen("file.txt", "rt");

char buffer[1024];

fgets(buffer, sizeof(buffer), fp);

fclose(fp);



// now we do some editing action:

strcpy(&buffer[18], &buffer[23]);

// This would result in buffer containing "Hello World, here I am"

// This deletes any content of file.txt

fp = fopen("file.txt", "wt");



// This writes edited content back to the file

fprintf(fp, buffer);

fclose(fp);

fp = NULL;
bernmeister
2010-03-20 07:25:14 UTC
C doesn't have much library support. That, plus that fact that PC's these days have lots of RAM, etc, the brute-force approach is the easiest to code. Here's a high-level approach:



1) fopen the file in read ("r") mode.

2) In a while loop, read every char (fgetchar) until you hit end of file. Count number of reads /w integer. Purpose is to get file size.

3) Close file.

4) malloc() a chunk of memory that's the size of the file.

5) fopen the file again in read mode.

6) copy contents of file into ram buffer.

7) close file

8) Do your text deleting in the ram buffer. Readjust buffer size integer when finished.

9) fopen file in write ("w") mode

10) copy ram buffer back to file, using readjusted buffer size.

11) close file
Germann A
2010-03-20 02:54:27 UTC
Open the file in "w" (write) mode instead of "a" (append) mode.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...