zoukankan      html  css  js  c++  java
  • 文件输入输出

    C++的I/O流

    C++的I/O流是带有缓冲的,使用 get()/getline()等函数,了解缓冲对输入的影响

    调用文件流类中的get()函数读文件内容,文件位置指示器会向文件尾部移动一个单位,get函数读的是一个字符,移动的单位是一个字节

    win10系统,因为访问C盘需要管理员权限,使用ostream 对象无法在该盘创建文件。

    C++17 标准  filesystem类库

    filesystem,提供了path类,可以直接处理与文件路径相关的操作,也可以获取磁盘的相关信息

    namespace fs = std::filesystem;
    
    fs::path p{ "CheckPath.cpp" };
    namespace fs = std::filesystem;
    
    fs::path p1("d:\cpp\hi.txt"); // 字符串中的反斜杠要被转义
    
    fs::path p2("d:/cpp/hi.txt");   // Windows也支持正斜杠
    
    fs::path p3(R"(d:cpphi.txt)");// 使用原始字符串字面量

    Absolute Path (platform dependent) (绝对路径):

      An absolute path contains a file name with its complete path and drive letter.(包含完整的路径和驱动器符号)

    Relative Path (相对路径)

      (1)     Contains NO drive letter or  leading "/" (不包含驱动器及开头的/符号)

      (2)     The file stores in the path Relative to "Current Path" (文件存在相对于“当前路径”的位置)

    二进制输入输出

    用write()和read()这两个函数,这两个函数接收的第一个参数是 char*类型的指针

    将数组、整型变量等等与char*类型指针转换, reinterpret_cast<char*>(&x)

    随机文件访问

    文件读写

     1 #include <iostream>
     2 #include <fstream>
     3 #include <string>
     4 
     5 int main() 
     6 {
     7     //1.向文件写数据 ofstream
     8     std::ofstream out("d:\test.txt");
     9     std::string name;
    10     int i = 10;
    11     //写数据
    12     while(i--){
    13         std::cin>>name; //键盘输入字符串
    14         out << name <<"
    "; //写入文件
    15     }    
    16     //关闭文件
    17     out.close();
    18     
    19     //2.从文件读数据 ifstream
    20     std::ifstream in("d:\test.txt");
    21     
    22     /*std::cin>>i;
    23     if(i<1 || i>10){
    24         std::cout<<"error"<<std::endl;
    25         exit(0);
    26     }
    27      //读数据
    28     while (i--) {
    29         in>>name; //读文件到字符串
    30         std::cout<<name<<" "; //字符串输出到屏幕
    31     } */
    32     
    33     while (in.eof() == false) {
    34         std::cout << static_cast<char>(in.get());
    35     }
    36     
    37     //关闭文件
    38     in.close();
    39     
    40     return 0;
    41 }
  • 相关阅读:
    刷题19. Remove Nth Node From End of List
    刷题17. Letter Combinations of a Phone Number
    mysql图形化工具基本操作
    报错:ER_NO_DEFAULT_FOR_FIELD: Field 'status' doesn't have a default value
    express综合用法
    npm自定义上传
    node_第三方包下载文件package.jon详解
    正则表达式修改文字元素对齐方式
    初始化文章分类的方法 下拉的layui框
    标准git请求
  • 原文地址:https://www.cnblogs.com/GoldenEllipsis/p/11106816.html
Copyright © 2011-2022 走看看