C ++中的简单文件写入功能 [英] Simple file write function in C++

查看:55
本文介绍了C ++中的简单文件写入功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    writeFile();
}

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

为什么这不起作用?它给了我错误:

Why is this not working? it gives me the error:

1>------ Build started: Project: FileRead, Configuration: Debug Win32 ------
1>  file.cpp
1>e:\documents and settings\row\my documents\visual studio 2010\projects\fileread\fileread\file.cpp(8): error C3861: 'writeFile': identifier not found
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

这只是一个简单的功能.我正在使用Visual Studio 2010.

and this is just a simple function. I'm using Visual Studio 2010.

推荐答案

对此有两种解决方案.您可以将方法放在调用它的方法之上:

There are two solutions to this. You can either place the method above the method that calls it:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

int main()
{
    writeFile();
}

或声明原型:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int writeFile();

int main()
{
    writeFile();
}

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

这篇关于C ++中的简单文件写入功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆