remove

From cppreference.com
< c‎ | io
Defined in header <stdio.h>
int remove( const char *fname );

Deletes the file identified by character string pointed to by fname.

Contents

[edit] Parameters

fname - pointer to a null-terminated string containing the path identifying the file to delete

[edit] Return value

0 upon success or non-zero value on error.

[edit] Example

remove with error checking. Code removes an existing file, then tries to remove a nonexisting file.

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char* file_name = "C:\\file.txt";
 
    FILE *fp = fopen(file_name,"w");
    if (fp == NULL)
    {
      perror("fopen()");
      fprintf(stderr,"fopen() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
      exit(EXIT_FAILURE);
    }
 
    /* Normal processing continues here. */
    fclose(fp);
 
    system("ls");
 
    /* Remove an existing file. */
    int ret_code = remove(file_name);
    if (ret_code != 0)
    {
      perror("remove()");
      fprintf(stderr,"remove() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
      exit(EXIT_FAILURE);
    }
 
    system("ls");
 
    /* Try removing a nonexisting file. */
    ret_code = remove(file_name);
    if (ret_code != 0)
    {
      perror("remove()");
      fprintf(stderr,"remove() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
      exit(EXIT_FAILURE);
    }
 
    return EXIT_SUCCESS;
}

Output:

remove(): No such file or directory
remove() failed in file main.cpp at line # 33
C:\file.txt
a.out
main.cpp
a.out
main.cpp

[edit] See also

renames a file
(function)
C++ documentation for remove