文件-如何选择文件,程序显示其中的内容? [英] file - How i can select the file and my program show the things in it?

查看:73
本文介绍了文件-如何选择文件,程序显示其中的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "stdafx.h"
#include<iomanip>
#include <fstream>
#include<iostream>
using namespace std;
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
    ifstream inFile;
    inFile.open("C:\\Users\Public\Documents\c++ test for overloading\alaki\test.data");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1);
    inFile.close();
    return 0;
   }
}


如何选择文件并让程序显示其中的内容?


How I can select the file and let my program show the things in it?

推荐答案

如果从控制台进行操作,则可以使用cin进行操作.获取输入.
您可以使用读取块并将其显示或将其添加到字符串中的循环来读取内容

If you are doing it from the console, then you can use cin to get input.
You can use a loop of reading chunks and displaying it or adding it to a string to read the contents

#include <iomanip>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
    ifstream inFile;
    string file;
    cout << "Enter a file name:" << endl;
    cin >> file;
    //All \ need to be escaped with a 2nd \ like "C:\\Users\\Public\\Documents\\c++ test for overloading\\alaki\\test.data"
    inFile.open(file.c_str());
    if (!inFile.is_open()) { //you cant check the class for inequality... you need to call the is_open() method to see if it opened properley
        cout << "Unable to open file";
        //inFile.close(); //dont need to close... it never opened
        return -1; //you dont need exit and a return
    }
    char szContents[128]; //This can be any size you like. Dont make it too big (say more than 4096) unless you use new or malloc to create it.
    while (!inFile.eof()) {
        memset(szContents, 0, sizeof(szContents)); //empty the buffer
        inFile.read(szContents, sizeof(szContents) - 1); //include space for terminator
        cout << szContents;
    }
    inFile.close();
    return 0;
}


不确定确切的内容,但是要访问文件,请注意,所有反斜杠必须用字符串文字转义;您仅在
Not sure exactly what you''re after, but as far as accessing files, note that all backslashes must be escaped in a string literal; you have escaped only the first backslash in
inFile.open("C:\\Users\Public\Documents\c++ test for overloading\alaki\test.data"); 

中的第一个反斜杠转义了.

.


这篇关于文件-如何选择文件,程序显示其中的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆