2013-03-24 74 views
0

这里是创建目录的代码,它是switch case,因此我将它放在一个块内。读取文件中写入的目录位置,并在C++中创建该目录中的新文件。

{ 
int index = 0 ; 

char path[60]; 

system (" cls ") ; 

ofstream ofile ; 

cout < < " \ n Enter path to store bills 

< <(! Without spaces after symbols like slashes and colons 

< <e.g. \" c : \\ billing folder \\ \" : "; 

fflush (stdin) ; 

cin.getline (path , 60) ; 

mkdir (path) ; 

ofile.open (" Path.dat " , ios :: trunc | ios :: out | ios :: binary) ; 

ofile.write (path , strlen (path)); 

ofile.close () ; 

goto here1 ; 

} 

,这里是在上面创建的目录创建一个文件中的代码,该文件名必须是当前的日期和针对我已经使用的ctime头时间。

void billingWindow () 
{ 
system ("cls ") ; 

char path [ 60 ] ; 

char folder [ 30 ]; 

struct tm *timeInfo; 

time_t now; 

time(&now); 

timeInfo=localtime(&now); 

strftime(folder,30,"%d_%m_%y %H=%M",timeInfo); 


folder [ 14 ] = ' \0 ' ; 

string foldName (folder , 14) ; 

int index = 0 ; 

ifstream readFile (" Path.dat ", ios :: in) ; 

readFile.seekg (0 , ios :: end) ; 

int length = readFile.tellg () ; 

readFile.seekg (0 , ios :: beg) ; 

while (index <= (length-1)) 

{ 

    readFile.read (&path [ index ] , sizeof (char)) ; 

    index++ ; 
} 

path [ index ] = '\0'; 

char *newPath = new char [ index ] ; 

strcpy (newPath , path) ; //copied into 'newPath' because value of 'path' was showing garbage at it's tail while debugging and watching 

index = 0 ; 

strcat (newPath, foldName.c_str ()) ; //appended newPath with the current date and time stored in 'foldName' 

char alpha[ 80 ] ; 

strcpy (alpha ,newPath) ; //copied in the newPath in alpha because i was not sure of dynamically alloted character pointer's behaviour to create file 

delete [ ] newPath; 

ofstream writeBill (alpha , ios :: out) ; 

if (! writeBill) 
{ 

    cout < < " Error Occured "< < endl ; 
} 

目录创建成功,创建目录的代码也正确创建了包含路径的文件。每当我在我的IDE(codeBlocks)中运行调试器时代码工作正常,但运行代码来测试它或运行由IDE程序生成的可执行文件时,只会崩溃当我选择billingWindow选项

是否有任何致命错误在代码,请帮我

+0

没有错误检查处理该文件的任何函数。如果你添加错误检查你可能会发现什么是错的, – suspectus 2013-03-24 15:36:26

回答

0

这是错误的

char *newPath = new char[index]; 

你应该有

char *newPath = new char[index + foldName.size() + 1]; 

因为使用C风格的字符串你总是必须分配足够的内存来容纳所有的角色。

因为这很困难,所以应该总是使用C++字符串。例如。

std::string newPath = path; 
newPath += foldName; 

这是正确的,更短的,更容易编写和更容易理解。

+0

感谢解决方案 – Udit 2013-03-24 16:19:08