Show toolbar

2013年7月8日 星期一

Two ways to Read and Write Files

標題:C/C++兩種讀取文字檔的方法
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
//#include <iomanip>
//setprecision(4) "3.1415"
//setfill('Q') "QQ123"
//setw(5) "  123"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 0, j = 0;
    const char *filePath = "pi.xls";

    remove(filePath); //Delete File
    
    //VC++ -----------------------------------------------------

    //Write File
    ofstream outputFile(filePath, fstream::app); //fstream::out fstream::app
    if (outputFile.is_open()) //Check File
    {
        for(j=1;j<10;j++)
        {
            for(i=1;i<10;i++)
            {
                outputFile << i << "*" << j << "=" << i*j << "\t";
            }
            outputFile << endl;
        }
        outputFile.close();
    }

    //Read File
    string lines = "";
    ifstream inputFile(filePath);
    if (inputFile.is_open()) //Check File
    {
        while(inputFile.good())
        {
            getline(inputFile, lines);
            cout << lines << endl;
        }
        inputFile.close();
    }

    //Standard C -----------------------------------------------------

    //Write File
    FILE *writeFile = fopen(filePath, "a");
    if (writeFile) { //Check File
        for(j=1;j<10;j++)
        {
            for(i=1;i<10;i++)
            {
                fprintf(writeFile, "%d*%d=%d\t", i, j, i*j);
            }
            fprintf(writeFile, "\n");
        }
        fclose(writeFile);
    }
    
    //Read File
    char line[100] = ""; // Light!!
    FILE *readFile = fopen(filePath, "r");
    if (readFile) { //Check File
        while(fgets(line, sizeof(line), readFile))
        {
            printf("%s", line);
        }
        fclose(readFile);
    }

    return 0;
}

說明:
使用fstream的方法讀寫檔案,以及使用C的fopen讀寫檔案的方法。

沒有留言:

張貼留言