Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple file write function in C++ [duplicate]

Tags:

c++

I have this code:

// 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 ==========

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

like image 360
Master345 Avatar asked Jan 14 '12 16:01

Master345


People also ask

How do you copy one file to another?

Highlight the files you want to copy. Press the keyboard shortcut Command + C . Move to the location you want to move the files and press Command + V to copy the files.


3 Answers

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();
}

Or declare a prototype:

// 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;
}
like image 104
Tudor Avatar answered Oct 05 '22 05:10

Tudor


Your main doesn't know about writeFile() and can't call it.

Move writefile to be before main, or declare a function prototype int writeFile(); before main.

like image 41
Igor Avatar answered Oct 05 '22 07:10

Igor


You need to declare the prototype of your writeFile function, before actually using it:

int writeFile( void );

int main( void )
{
   ...
like image 30
Macmade Avatar answered Oct 05 '22 06:10

Macmade