We will discuss about four file hacks listed as below-
- Rename – Rename a file using C/C++
- Remove – Remove a file using C/C++
- File Size – Get the file size using C/C++
- Check existence – Check whether a file exists or not in C/C++
C++
#include <iostream>
#include <stdlib.h>
using namespace std;
unsigned long long int fileSize( const char *filename)
{
FILE *fh = fopen (filename, "rb" );
fseek (fh, 0, SEEK_END);
unsigned long long int size = ftell (fh);
fclose (fh);
return size;
}
bool fileExists( const char * fname)
{
FILE *file;
if (file = fopen (fname, "r" ))
{
fclose (file);
return true ;
}
return false ;
}
int main()
{
cout << fileSize( "Passwords.txt" ) << " Bytes\n" ;
cout << fileSize( "Notes.docx" ) << " Bytes\n" ;
if (fileExists( "OldData.txt" ) == true )
cout << "The File exists\n" ;
else
cout << "The File doesn't exist\n" ;
rename ( "Videos" , "English_Videos" );
rename ( "Songs" , "English_Songs" );
remove ( "OldData.txt" );
remove ( "Notes.docx" );
if (fileExists( "OldData.txt" ) == true )
cout << "The File exists\n" ;
else
cout << "The File doesn't exist\n" ;
return 0;
}
|
C
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
unsigned long long int fileSize( const char *filename)
{
FILE *fh = fopen (filename, "rb");
fseek (fh, 0, SEEK_END);
unsigned long long int size = ftell (fh);
fclose (fh);
return (size);
}
bool fileExists( const char * fname)
{
FILE *file;
if (file = fopen (fname, "r"))
{
fclose (file);
return ( true );
}
return ( false );
}
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");
else
printf ("The File doesn't exist\n");
rename ("Videos", "English_Videos");
rename ("Songs", "English_Songs");
remove ("OldData.txt");
remove ("Notes.docx");
if (fileExists("OldData.txt") == true )
printf ("The File exists\n");
else
printf ("The File doesn't exist\n");
return 0;
}
|
Output:
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 review-team@geeksforgeeks.org. 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