在c++中读取写在文件中的目录位置,并在该目录中创建新文件
to read the directory location written in file and to create new files in that directory in c++
下面是创建目录的代码,它是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;
正确,更短,更容易写,更容易理解。
相关文章:
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 从文件中读取多行.txt字符串删除空格并创建新文件进行输出
- 如何限制文件大小,以便我的程序在变大之后创建一个新文件?并编辑新创建的文件的名称
- 需要更新Qt .pro和Visual Studio .vcxproj添加新文件
- C 如何将二进制文件的一部分复制到新文件
- 将单词写入新文件
- Clang 使用 LibTooling Rewriter 生成新文件
- 从Ubuntu中的CPP程序创建新文件
- Windows Portable设备 - 创建 /复制 /删除新文件时通知
- 代码块在尝试编译或创建新文件时出现"An assertion failed!"错误
- C++,打开和编辑文本文件中的数字数据,并将结果放入新文件中
- C++读取添加到目录中的新文件
- boost::log关闭日志文件并打开一个新文件
- 可执行文件无法在双击执行时创建新文件
- 如何知道何时将新文件添加到 Windows 中的文件系统
- 流未正确创建新文件
- 使用std :: ifstream打开一个新文件
- 从一个字符串复制到另一个字符串并粘贴到新文件中
- inotify 的替代方法,用于检测何时在文件夹下创建新文件
- 此项目不会将整数读取为二进制并将其作为二进制输出到新文件