Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 135 ยท File Input and Output

Deleting, Renaming and Temporary Files

Delete and rename files with remove and rename, create temporary files safely with tmpfile and mkstemp, and avoid the classic while(!feof) bug when reading.

So far you have created, written and read files. A real program also has to manage them: remove a file it no longer needs, rename a finished report, keep scratch data in a temporary file, and detect correctly when a read has reached the end. The standard library covers each of these with a small function, and each has a trap worth knowing about.

All the examples run in the sandbox's working directory, which starts empty on every run, so each program builds the files it needs first.

remove: deleting a file

int remove(const char *path) deletes the file named by path. It returns 0 on success and a nonzero value on failure, with the reason in errno. Deleting is permanent: there is no recycle bin, so check the path before you pass it.

The function works on a name, not an open stream. If the file is still open elsewhere, the standard says the behavior is implementation-defined. On Linux the name disappears at once and the data lives until the last handle is closed; on Windows the call usually fails. Close the file before you remove it.

rename: moving or renaming

int rename(const char *old, const char *new) gives a file a new name, or moves it to another folder on the same file system. It returns 0 on success. If new already exists, the result depends on the platform: on POSIX systems the old destination is silently replaced in one atomic step, which is useful (you can safely update a file by writing a new copy and renaming it over the old one), but on Windows the call fails instead.

C remove and rename with error reporting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The second remove fails with No such file or directory (ENOENT), which is a normal, expected failure when the goal is simply "make sure it's gone". Programs often treat ENOENT as success for deletions and report every other error code.

There is no standard "does this file exist?" function. Opening it with fopen(name, "r"), as above, is the portable check. It also fails when the file exists but you may not read it, so use errno to tell the cases apart. POSIX offers access and stat.

Temporary files

Programs sometimes need scratch space: sorted chunks of a huge file, an intermediate result, a scratch download. The standard library offers three approaches, with very different safety.

tmpfile() (in <stdio.h>) creates a uniquely named file opened in "wb+" mode and returns the FILE *. The file is removed automatically when you fclose it or when the program ends normally. You never see the name, so no one can guess it. This is the best choice whenever you only need the data inside your own program.

tmpnam returns a name that does not exist at the moment of the call. Between that call and your fopen, another process can create a file with the same name (a race), and an attacker can plant a link there. Compilers warn about it, and you should treat it as obsolete.

mkstemp (POSIX, in <stdlib.h>) is the safe way to get a named temporary file. You pass a template ending in XXXXXX; the function replaces those characters with random ones, creates the file exclusively with owner-only permissions and returns an open file descriptor. Use fdopen to turn it into a FILE *. Remember to remove the file yourself when you finish.

C tmpfile and mkstemp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The template is a character array, not a string literal, because mkstemp writes into it. The actual random name changes on every run, so the example prints facts about it instead of the name itself. If your program might crash before cleaning up, put the temporary files in a dedicated directory so stale ones are easy to find.

Detecting the end of a file correctly

Every input function reports two different outcomes with the same signal: "no more data" and "something went wrong". After a read fails, ask the stream which one it was:

  • feof(fp) is true when a read tried to go past the end of the file.
  • ferror(fp) is true when a read hit an I/O error.

The mistake that fills Q&A sites is using feof as the loop condition. feof becomes true only after a read has already failed, so the loop body runs once more with stale data:

C The while (!feof) bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The wrong loop prints grace twice: after the third line is read, the end-of-file flag is still clear, so the loop runs once more; fgets fails, leaves the buffer unchanged and the program prints the old contents again. The right loop tests the return value of the read function and only afterwards uses feof and ferror to explain why the loop stopped. The same applies to fread, fscanf (compare against the number of conversions you expect) and getc (compare against EOF, and store it in an int, not a char).

File programs: copy, append, compare, search and read-only

A handful of file utilities come up in every course. Each one is a small loop over fgetc, fread or fgets; the skill is checking every return value and closing every file on every path.

  • Copy reads blocks with fread and writes the same number of bytes with fwrite. Use binary mode ("rb", "wb") so nothing is translated.
  • Append opens with "a", which writes every byte at the current end of the file.
  • Compare reads both files one byte at a time and stops at the first difference. Report the byte offset, and treat "one file ended first" as a difference.
  • Search (a tiny grep) reads lines with fgets and prints the ones where strstr finds the pattern.
  • Make a file read-only has no standard function. POSIX has chmod(path, 0444) in <sys/stat.h>; on Windows it is _chmod with _S_IREAD. Opening a read-only file for writing then fails with EACCES, unless you run as an administrator.
C Copy, append, compare, search and chmod

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

After the append, a.txt ends at byte 17 while b.txt continues, so the first mismatch is at offset 17: one file hits EOF while the other still has d. In the search, both beta and delta contain ta, and gamma does not. copy_file checks fclose(out) too, because buffered data is written (and can fail) when the file is closed. The final fopen fails with Permission denied because the file is read-only for this user; as root (or an administrator) it would succeed, so do not rely on permission bits to protect data from privileged code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does remove("data.txt") return when the file does not exist?

    remove returns nonzero on any failure and stores the reason in errno; a missing file gives ENOENT.
  2. 2. Which function gives you a temporary file whose name nobody can predict and that deletes itself when closed?

    tmpfile creates an anonymous file that is removed on fclose or normal program exit. tmpnam only produces a name, which is prone to races.
  3. 3. What must the argument of mkstemp look like?

    mkstemp overwrites the trailing XXXXXX in place, so the template must be a writable array, not a string literal.
  4. 4. Why is while (!feof(fp)) { fgets(...); ... } wrong?

    The end-of-file flag is set by a read that hits the end. The loop must test the return value of the read, then use feof or ferror afterwards.
  5. 5. On POSIX systems, what happens when rename's destination already exists?

    POSIX rename replaces an existing destination in one atomic step. Windows behaves differently, so portable code should not depend on it.

Summary

  • remove(path) deletes a file permanently and returns 0 on success; rename(old, new) renames or moves it, replacing an existing target on POSIX systems but failing on Windows.
  • Close a file before removing or renaming it, and report failures with errno and strerror.
  • tmpfile() gives an anonymous scratch file that cleans itself up; mkstemp with an XXXXXX template is the safe way to get a named one; avoid tmpnam.
  • Never loop on feof. Test the return value of the read function (fgets, fread, getc), then use feof and ferror to learn why it stopped.

Next: System Calls, where you go below the standard library to talk to the operating system directly.