注册 登录
编程论坛 C++教室

一个文件读写问题来求教了

tonlin 发布于 2010-05-27 13:16, 512 次点击
程序代码:

#include "stdafx.h"
#include "fstream"
#include "iostream"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{  
    char ch,a[100];
    ifstream file1;
    ofstream file2;
    file1.open("file1.txt",ios::in);   
    if(file1)
    {
       int i=0;
        while((ch=file1.eof())==0)
       {
        file1.getline(a,100);
        cout<<a<<endl;
        file2.open("file2.txt",ios::out|ios::app);
        file2<<i+1<<":"<<a<<endl;
        file2.close();
        i++;
       }            
    }
    else
     cout<<"文件打开失败"<<endl;
    file1.close();      
    return 0;
}
以上代码目的将file1文件内容逐行读取出来读出一行后打开文件file2将读出内容写入file2中。
程序编译通过但是读出内容没有写到file2中,这是为什么?请高手帮忙回答下,谢谢了


[ 本帖最后由 tonlin 于 2010-5-27 13:27 编辑 ]
2 回复
#2
ciweitou1632010-05-27 19:16
程序代码:
#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{  
    char ch,a[100];
    ifstream file1;
    ofstream file2;
    file1.open("file1.txt",ios::in);   
    if(file1)
    {
       int i=0;
        while((ch=file1.eof())==0)
       {
        file1.getline(a,100);
        cout<<a<<endl;
        file2.open("file2.txt",ios::out|ios::app);
        file2<<i+1<<":"<<a<<endl;
        file2.close();
        i++;
       }            
    }
    else
     cout<<"文件打开失败"<<endl;
    file1.close();      
    return 0;
}

我运行的时候没问题啊,在程序的同一级目录下建立file1.txt
然后 运行能读出文件,也能输出到file2.txt中。
#3
tonlin2010-06-02 19:03
回复 2楼 ciweitou163
额。那是为什么捏
1