Skip to content
Related Articles

Related Articles

Four File Handling Hacks which every C/C++ Programmer should know

Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 29 May, 2017

We will discuss about four file hacks listed as below-

  1. Rename – Rename a file using C/C++
  2. Remove – Remove a file using C/C++
  3. File Size – Get the file size using C/C++
  4. Check existence – Check whether a file exists or not in C/C++

// A C++ Program to demonstrate the
// four file hacks every C/C++ must know
// Note that we are assuming that the files
// are present in the same file as the program
// before doing the below four hacks
// A Function to get the file size
unsigned long long int fileSize(const char *filename)
    // Open the file
    FILE *fh = fopen(filename, "rb");
    fseek(fh, 0, SEEK_END);
    unsigned long long int size = ftell(fh);
    return (size);
// A Function to check if the file exists or not
bool fileExists(const char * fname)
    FILE *file;
    if (file = fopen(fname, "r"))
        return (true);
    return (false);
// Driver Program to test above functions
int main()
    printf("%llu Bytes\n", fileSize("Passwords.txt"));
    printf("%llu Bytes\n", fileSize("Notes.docx"));
    if (fileExists("OldData.txt") == true )
        printf("The File exists\n");
        printf("The File doen't exist\n");
    rename("Videos", "English_Videos");
    rename("Songs", "English_Songs");
    if (fileExists("OldData.txt") == true )
        printf("The File exists\n");
        printf("The File doesn't exist\n");
    return 0;


Screenshot before executing the program :

Screenshot after executing the program :

This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

My Personal Notes arrow_drop_up

Start Your Coding Journey Now!