0

here is the code for creating the directory it is switch case so i have placed it inside a block.

{
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 ;

}

and here is the code to create a file in the directory created above,the file name have to be the current date and time for which i have used ctime header.

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

creation of directory is successful and the code to create directory also created the file containing path properly. whenever i run the debugger in my IDE(codeBlocks) the code works fine but while running the code to test it or running the executable made by IDE program just crash when i select the option to the billingWindow

is there any fatal error in the code,please help me

4

1 回答 1

0

这是错误的

char *newPath = new char[index];

你应该有

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

因为对于 C 风格的字符串,您总是必须分配足够的内存来保存所有字符。

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

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

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

于 2013-03-24T15:36:52.697 回答