C++檔案讀寫代碼分享_C 語言

來源:互聯網
上載者:User

編寫一個程式,統計data.txt檔案的行數,並將所有行前加上行號後寫到data1.txt檔案中。

演算法提示:

行與行之間以斷行符號符分隔,而getline()函數以斷行符號符作為終止符。因此,可以採用getline()函數讀取每一行,再用一個變數i計算行數。

(1)實現原始碼

#include <iostream>#include <fstream>#include <string>#include <sstream> using namespace std; int coutFile(char * filename,char * outfilename){  ifstream filein;  filein.open(filename,ios_base::in);  ofstream fileout;  fileout.open(outfilename,ios_base::out);  string strtemp;  int count=0;  while(getline(filein,strtemp))  {    count++;    cout<<strtemp<<endl;    fileout<<count<<" "<<strtemp<<endl;  }  filein.close();  fileout.close();  return count;}  void main(){  cout<<coutFile("c:\\data.txt","c:\\data1.txt")<<endl;}

再來一個樣本:

下面的C++代碼將使用者輸入的資訊寫入到afile.dat,然後再通過程式讀取出來輸出到螢幕

#include <fstream>#include <iostream>using namespace std;  int main (){     char data[100];   // open a file in write mode.  ofstream outfile;  outfile.open("afile.dat");   cout << "Writing to the file" << endl;  cout << "Enter your name: ";  cin.getline(data, 100);   // write inputted data into the file.  outfile << data << endl;   cout << "Enter your age: ";  cin >> data;  cin.ignore();     // again write inputted data into the file.  outfile << data << endl;   // close the opened file.  outfile.close();   // open a file in read mode.  ifstream infile;  infile.open("afile.dat");    cout << "Reading from the file" << endl;  infile >> data;   // write the data at the screen.  cout << data << endl;     // again read the data from the file and display it.  infile >> data;  cout << data << endl;   // close the opened file.  infile.close();   return 0;}

程式編譯執行後輸出如下結果

$./a.outWriting to the fileEnter your name: ZaraEnter your age: 9Reading from the fileZara9

以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.