📌  相关文章
📜  每个C / C++程序员都应该知道的四个文件处理技巧

📅  最后修改于: 2021-05-26 00:04:50             🧑  作者: Mango

我们将讨论以下列出的四个文件黑客:

  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
#include
#include
  
// 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\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 doen'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;
}

输出:
cfile3

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

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

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”