在c++中读取写在文件中的目录位置,并在该目录中创建新文件

to read the directory location written in file and to create new files in that directory in c++

本文关键字:文件 新文件 创建 读取 c++ 位置      更新时间:2023-10-16

下面是创建目录的代码,它是switch case,所以我把它放在一个块中。

{
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 ] = '  ' ;
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 ] = '';
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

选项时,会崩溃。

代码中是否有致命错误,请帮助我

这是错误的

char *newPath = new char[index];

你应该有

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

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

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

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

正确,更短,更容易写,更容易理解。