2011-04-30 193 views
0

我正在創建一個程序來複制文本文件。我有一個main.cpp文件,它讀入由文件名數組給出的文本文件,然後輸出由文件名數組給出的文本文件的副本。我在我的FileUtilities.h聲明此功能Visual C++斷言失敗

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

然後FileUtilities.cpp包含

#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; 
} 

當我編譯此,我得到一個Visual C斷言失敗。我收到標題爲 「微軟的Visual C++調試庫」 對話框,包含以下:

「調試斷言失敗

計劃:..... Parser.exe

文件f: \ DD \ vctools \ crt_bld \ Self_x86 \ CRT \ SRC \ fopen.c

線53

表達:(!文件= NULL)」

此錯誤給了我3個選項:中止,重試或忽略。 中止只是停止調試。重試會在Visual Studio中顯示一條消息,其中提示「program.exe觸發了一個斷點」。如果我在這裏單擊中斷,Visual Studio將打開一個名爲「fopen.c」的文件並指向此文件中的第54行。

如果我從這個角度Visual Studio中繼續打開名爲「dbghook.c」的指針線62

+0

好,很明顯, 'filenamein'或'filenameout'是NULL指針。向我們展示如何調用'textFileCopy'。 – 2011-04-30 20:35:43

+0

你應該以大塊而不是char字符拷貝文件。 – 2011-04-30 20:45:52

回答

3

哪裏錯誤另一個文件?在finfout?檢查相應的filenameXX,它一定不是NULL

+0

我現在修復了它,文件名在我的main.cpp文件中被設置爲null。謝謝 – Marc 2011-04-30 20:48:24

+0

不客氣(:祝你好運;) – 2011-04-30 20:49:13

2

filenameinfilenameout out都是空的,因此是錯誤的。如果使用std::string而不是C字符串,則不必擔心空指針。由於您已經在使用C++ I/O庫,因此沒有理由不使用std::string

也就是說,你的函數也是不正確的,因爲在使用提取的字符之前,你沒有檢查get()調用是否成功。即使副本在部分文件中失敗,也會返回true

下面是一個正確的實現這個功能的(但是請注意,這是幾乎肯定不是最佳的,它只是演示瞭如何正確地寫你具備的功能):

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