你如何用C ++打开文件? [英] How do you open a file in C++?

查看:399
本文介绍了你如何用C ++打开文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个用于阅读的文件,即C ++方式。我需要能够做到:

I want to open a file for reading, the C++ way. I need to be able to do it for:


  • 文本文件,这将涉及某种读取线功能。

  • text files, which would involve some sort of read line function.

二进制文件,它提供了一种将原始数据读入 char * 缓冲区的方法。

binary files, which would provide a way to read raw data into a char* buffer.

推荐答案

根据您的需要,有三种方法可以做到这一点。您可以使用旧式C语言并调用fopen / fread / fclose,或者您可以使用C ++ fstream工具(ifstream / ofstream),或者如果您使用的是MFC,请使用CFile类,它提供了实现实际的功能文件操作。

There are three ways to do this, depending on your needs. You could use the old-school C way and call fopen/fread/fclose, or you could use the C++ fstream facilities (ifstream/ofstream), or if you're using MFC, use the CFile class, which provides functions to accomplish actual file operations.

所有这些都适用于文本和二进制文件,但没有一个具有特定的readline功能。在这种情况下你最有可能做的是使用fstream类(fstream.h)并使用流操作符(<<和>>)或read函数来读/写文本块:

All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:

int nsize = 10;
char *somedata;
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata,nsize);
myfile.close();

请注意,如果您使用的是Visual Studio 2005或更高版本,则可能无法使用传统的fstream(有一个新的Microsoft实现,略有不同,但完成相同的事情。)

Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing).

这篇关于你如何用C ++打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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