Question

I am creating a program to copy a text file. I have a main.cpp file which reads in a text file given by the filenamein array and then output a copy of the text file given by the filenameout array. i have this function declared in my FileUtilities.h as

bool textFileCopy(char filenamein[], char filenameout[]);

Then the FileUtilities.cpp contains

#include <iostream>
#include <fstream>
#include <string>

#include "FileUtilities.h"

bool FileUtilities::textFileCopy(char filenamein[], char filenameout[])
{
    ifstream fin(filenamein);
    if(fin.is_open())
    {
        ofstream fout(filenameout);

        char c;
        while(fin.good())
        {
            fin.get(c);
            fout << c;
        }

        fout.close();
        fin.close();

        return true;
    }
    return false;
}

When I compile this I get a Visual C assertion failure. I get a dialog box titled "Microsoft Visual C++ debug library" which contains the following:

"Debug Assertion Failed!

Program: .....Parser.exe

file f:\dd\vctools\crt_bld\Self_x86\crt\src\fopen.c

Line 53

Expression: (file!=NULL)"

This error gives me 3 options: Abort, Retry or Ignore. Abort just stops the debug. Retry brings up a message in Visual Studio which says "program.exe has triggered a breakpoint". If I click break here Visual Studio opens a file called "fopen.c" and points to line 54 in this file.

If I continue from this point Visual Studio opens another file called "dbghook.c" with a pointer to line 62.

Was it helpful?

Solution

Where's the error? On fin or fout? Check the corresponding filenameXX, it must not be NULL

OTHER TIPS

Either filenamein or filenameout out is null, hence the error. If you use std::string instead of C strings, you won't have to worry about null pointers. Since you are already using the C++ I/O library, there's really no reason not to use std::string.

That said, your function is also incorrect because you don't check whether the get() call succeeded before using the extracted character. You also return true, even if the copy fails part way through the file.

The following is a correct implementation of this function (note, however, that it is almost assuredly not optimal; it just demonstrates how to correctly write the function that you have):

bool textFileCopy(std::string filenamein, std::string filenameout)
{
    // Open the input stream
    std::ifstream in(filenamein.c_str());
    if (!in)
        return false;

    // Open the output stream
    std::ofstream out(filenameout.c_str());
    if (!out)
        return false;

    // Do the copy
    char c;
    while (in.get(c) && out.put(c));

    // Ensure that the whole file was copied successfully
    return in.eof() && out;

}   // The input and output streams are closed when the function returns
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top