天天看点

C++文件输入输出流的一点经验 In C programming language, the getchar() can get the ‘\n’ and ‘ ’, and putchar() can output this character. in addition, the scanf() and printf() can do the same thing. 文本方式的操作:二进制的操作:

http://www.cnblogs.com/CaiNiaoZJ/archive/2011/08/18/2144247.html this blog is in detail, many of the following contents are from it. See the blog first, you will get a lot more:

In C programming language, the getchar() can get the ‘\n’ and ‘ ’, and putchar() can output this character. in addition, the scanf() and printf() can do the same thing.      

<span style="font-weight: normal;">#include <stdio.h>

int main() {
	char a;

	a = getchar();
	putchar( a );
	putchar('x');
	getchar();
	return 0;
}</span>
           

文本方式的操作:

心得体会:

1、开一个输入一个输出,不能同时进行,必须先关一个才能进行下一个的操作,例如:

#include <fstream>
#include <string>
#include <iostream>
using namespace std;
 
int main()
{
    ofstream ocout;
    ifstream ocin;
    char str[100];
    
    ocout.open("test.txt"); //其实建立ifstream类和ofstream类的对象时,ios:in和ios:out可以省略,
    ocin.open("test.txt");  //因为ifstream类默认为ios:in,ofstream类默认为ios:out;

    ocout << "Hello,C++!";
    ocout.close();                     //这一行必须在ocin开始之前写
    
    while ( !ocin.eof() ) { 
        ocin.getline (str,100);
        cout << str << endl;
    }    
    
    ocin.close();
    system("pause");
    
    return 0;
}
           

只有当ofstream中的ocout已经close()之后,str才可以在屏幕中显示,开始习惯性的将ocout与ocin一起在代码的最后进行关闭,结果没办法输出,纠结了好久,结果发现是这个问题;

2、从file读入的时候,cin是以空格为分隔符,如果没有空格的话,将会可能出现一些不合理的现象!

3、从file进行写的操作结束的时候,文件指针指向的是最后一个字节的下一个,如果要重新读进内存的话,要将文件指针先移动到文件头,这样才可以读出来

4、我在进行fstream的实验的时候,发现了一个很奇怪的问题

#include <fstream>
#include <iostream>
using namespace std;

int main() {
    char str[100];
    char copy[100];
    
    fstream File ("test.txt", ios::in|ios::out);
    if ( !File ) {
        cout << "the File is not created!" << endl;
    }
    else {
        cin.getline (str, 100);
        File << str << endl;
        File.seekg( ios::beg );
        File.getline(copy, 100);
        cout << copy;
    }
    
    File.close();
    system("pause");
    
    return 0;
}    
        
           

结果在生成的txt文件中,第一个字符被复制了一次,例如输入:"Ilove you!",结果输出的是“II loveyou!”,但是很奇怪的是,str中的确存储的是正确的形式,并且读回来的时候是正确的,说明是文件流输出的操作出现了错误,这是什么原因呢?(解决办法:换了一台电脑,结果输出正确。。。不知如何是好。。。)

二进制的操作:

原因:

最初设计流的目的是用于文本,因此在默认情况下,文件用文本方式打开。在以文本模式输出时,若遇到换行符"\n"(十进制为10)则自动扩充为回车换行符(十进制为13和10)。所以,如果我们输入的整数10,那么在文件输出时会转化为13和10,然而这并不是我们所需要的。为了解决这样的问题,就要采用而二进制模式,使其所写的字符不转换。在对二进制文件进行IO操作时,打开文件时要指定方式ios::binary,即以二进制形式传送和存储。接下来我用read函数和write函数来对二进制文件进行读写。在示例描述之前先简单介绍一下这两个函数:

read函数常用格式为:文件流对象.read(char*buf,int len);

write函数常用格式为:文件流对象.write(constchar *buf,int len);

另外,一些打开方式入下图所示,以方便查询:

C++文件输入输出流的一点经验 In C programming language, the getchar() can get the ‘\n’ and ‘ ’, and putchar() can output this character. in addition, the scanf() and printf() can do the same thing. 文本方式的操作:二进制的操作:
<pre>
           

继续阅读