每个C/C++程序员都应该知道的四种文件处理技巧

我们将讨论下面列出的四种文件黑客-

null
  1. 重命名–使用C/C重命名文件++
  2. 删除–使用C/C删除文件++
  3. 文件大小–使用C/C获取文件大小++
  4. 检查是否存在–检查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
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
// 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);
fclose (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" ))
{
fclose (file);
return ( true );
}
return ( false );
}
// Driver Program to test above functions
int main()
{
printf ( "%llu Bytes" , fileSize( "Passwords.txt" ));
printf ( "%llu Bytes" , fileSize( "Notes.docx" ));
if (fileExists( "OldData.txt" ) == true )
printf ( "The File exists" );
else
printf ( "The File doen't exist" );
rename ( "Videos" , "English_Videos" );
rename ( "Songs" , "English_Songs" );
remove ( "OldData.txt" );
remove ( "Notes.docx" );
if (fileExists( "OldData.txt" ) == true )
printf ( "The File exists" );
else
printf ( "The File doesn't exist" );
return 0;
}


输出: cfile3

执行程序前的屏幕截图: cfile1

执行程序后的屏幕截图: cfile2

本文由 拉希特·贝尔瓦里亚 .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇文章,并将文章邮寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享