简体   繁体   English

C ++文件处理

[英]C++ File Handling

I Googled around, but didn't find any good example / tutorial. 我在Google周围搜索,但没有找到任何好的示例/教程。

So i asking you SOF: How do you Read and Write to a File in C++? 所以我问你SOF:如何用C ++读写文件?

That is interesting. 这太有趣了。 I typed How do you Read and Write to a File in C++ into google and found lots of results, like this one . 我打你怎么读取和写入文件在C ++到谷歌,发现很多结果,像这一个

Try using the fopen , fwrite , fread , and fclose functions for the most basic file I/O, eg 尝试对最基本的文件I / O使用fopenfwritefreadfclose函数,例如

#include <stdio.h>

int main(int argc, char** argv)
{
  FILE* f = fopen("hello world.txt", "wb");
  if(!f) return -1;
  fwrite("Hello World", sizeof(char), 11, f);
  fclose(f);
  return 0;
}

There are other functions that can help such as fprintf , fscanf , fputs and fgets . 还有其他可以帮助的功能,例如fprintffscanffputsfgets

如果您不喜欢自己做基本的文件处理,则可能需要看一下Boost库

You might look at things like fprintf() and fscanf(). 您可能会看fprintf()和fscanf()之类的东西。 But to get you started: 但是,为了让您入门:

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

#define SHOW(X) cout << # X " = " << (X) << endl

void write()
{
  ofstream o("filefoo");
  o << "test 1 2 3" << endl;
}

void read()
{
  ifstream i("filefoo");
  string s[4];
  i >> s[0] >> s[1] >> s[2] >> s[3];

  for( int j=0; j<4; j++ )
    SHOW(s[j]);
}

int main()
{
  write();
  read();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM