C++文件流操作

版权声明:本文为博主原创文章,转载请注明出处:https://blog.csdn.net/qq_31261509 https://blog.csdn.net/qq_31261509/article/details/84024531

读取文件


假如需要按行读取下列文件,并且分别通过不同变量读取路径以及数字,则可以通过C++流操作

/home/ubuntu/demo.jpg 1
/home/ubuntu/result.jpg 0

代码:

#include <iostream>
#include <fstream>

int main(int argc, char** argv) {
    std::ifstream infile(argv[1]);  // 通过传入参数输入路径, demo.txt
    std::string line;
    size_t pos;
    int label;
    std::string str;
    while (std::getline(infile, line)) {  // 从流中每次读取一行,并存入line中
        pos = line.find_last_of(' ');     // 找到空格位置
        label = atoi(line.substr(pos + 1).c_str()); // 空格后存储到label
        str = line.substr(0, pos);                  // 空格前存储到str
        std::cout << "label: " << label << "  path: " << str << std::endl;
    }
}



结果:

label: 1  path: /home/ubuntu/demo.jpg
label: 0  path: /home/ubuntu/result.jpg

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_31261509/article/details/84024531