0

ここにディレクトリを作成するためのコードがあります。これはスイッチケースであるため、ブロック内に配置しました。

{
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 のオプションを選択するとクラッシュします。

コードに致命的なエラーはありますか、助けてください

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 に答える