繁体   English   中英

当我尝试在某个目录中创建txt文件时,在其末尾有垃圾字符

[英]When i try to create a txt file in a certain directory there junk characters at then end of it

我正在尝试在目录中创建文件,最后有垃圾字符,这是我的代码:创建文件时,.txt之后有一些垃圾字符

char *path=strdup(argv[1]);//argv[1] is a number from 1-9
strcat(path,"/mynewfile.txt");
FILE *f=fopen(path,"w");
.....
fclose(f);

strdup会复制给定的char数组。 它只会分配足够的内存来容纳该字符串。 你不能strcat ,因为它会出界和不确定的行为会发生什么吧。

您需要为整个字符串分配足够的内存,然后strcpy第一部分, strcat后者。 只有这样才能定义行为。

例如:

char path[256];
strcpy(path, argv[1]);
strcat(path,"/mynewfile.txt");
FILE *f=fopen(path,"w");

请注意,您仍应确保分配的内存足够。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM