尝试向文件添加扩展名时,Rename() 函数不起作用
我有一个无扩展名的文件,我想为其添加 .avi
扩展名。因此,我在通过打开文件对话框选择文件后调用此函数(我想在重命名后打开文件):
int RenameVidAddExt(HWND hWnd, char oldname[MAX_PATH])
{
int filenamesize=0, n=0;
char extension [] = ".avi";
char* newname;
for (n=0 ; oldname[n]!=NULL ; n++)
{
filenamesize++;
}
newname = new char[filenamesize+sizeof(extension)];
newname = oldname;
strcat (newname, extension);
//SetDlgItemTextA(hWnd, IDC_EDIT1, szFile); //test print of filenameof selected file
//SetDlgItemTextA(hWnd, IDC_EDIT2, newname); //test print of newname
rename(oldname,newname);
return 0;
}
文件名没有改变,我不知道为什么。测试打印显示 oldname
和 newname
都包含正确的字符串(旧的不带扩展名,新的带扩展名)。
I have an extension-less file and I want to add an .avi
extension to it. So I call this function after selecting the file via openfile dialog (I want to have the file opened after renaming):
int RenameVidAddExt(HWND hWnd, char oldname[MAX_PATH])
{
int filenamesize=0, n=0;
char extension [] = ".avi";
char* newname;
for (n=0 ; oldname[n]!=NULL ; n++)
{
filenamesize++;
}
newname = new char[filenamesize+sizeof(extension)];
newname = oldname;
strcat (newname, extension);
//SetDlgItemTextA(hWnd, IDC_EDIT1, szFile); //test print of filenameof selected file
//SetDlgItemTextA(hWnd, IDC_EDIT2, newname); //test print of newname
rename(oldname,newname);
return 0;
}
The filename just doesn't change and I don't know why. Test prints show that both oldname
and newname
contain correct strings (old without extension and new with it).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您使用的是 C++,请考虑同时使用
std::string
:一些旁注:
new
或new[]
时,您必须稍后使用delete
或delete[]
(当使用new
或new[]
创建的对象不存在时)需要更长的时间)。std::string
。它将使您不必手动处理内存,并且可以将它们分配/复制到其他变量。std::vector
,而不是使用new[]
。将矢量大小调整为所需的大小。当您需要指向第一个元素的指针时,请使用&vec[0]
。使用std::vector
的好处是可以为您完成内存管理。strlen
这样的函数。或者,可以使用str.length()
获取std::string
的长度。Since you are using C++, consider also using
std::string
:Some side notes:
new
ornew[]
, you must usedelete
ordelete[]
later (when the object created withnew
ornew[]
is no longer needed).std::string
as much as possible. It will save you from having to handle memory manually, and they can be assigned / copied to other variables.new[]
, it is often recommended to usestd::vector
instead. Resize the vector to the desired size. When you require a pointer to the first element, use&vec[0]
. The benefit to using astd::vector
is that memory management is done for you.strlen
. Alternatively, the length of astd::string
can be obtained withstr.length()
.您无法通过分配指针值来复制 C 样式字符串。您的代码动态创建一个新的缓冲区,然后通过分配给该指针立即将其孤立。
我建议使用 std::string 代替。但是,如果您想继续使用 C 型琴弦,请尝试以下操作:
祝您好运!
You can't copy a C-style string by assigning pointer values. Your code dynamically creates a new buffer, then promptly orphans it by assigning to that pointer.
I suggest using std::string instead. However, if you want to stay with the C-style strings, try this:
Good luck!