【发布时间】:2021-09-26 23:56:04
【问题描述】:
我需要编写一个程序来使用系统调用创建一个文件。
输入文件名以宏的形式给出(#define filename "/log/data.log"`)。 我必须在文件名中添加一个数字,并根据需要将其更改为“/log/data_1.log 或 /log/data_2.log”。
我正在使用open() 创建文件。
#define filename "/log/data.log"
int fd=0;
int num; //This is the number I want to add to the file name
if(fd = open(file_name, O_RDWR | O_CREAT, 0666) ) < 0 )
{
printf("Could not open the log file: %s\n", strerror(errno) );
return -1;
}
【问题讨论】:
-
看看
sprintf() -
我尝试使用 sprintf 但它给出了分段错误
-
@HimajaKrishna 如果您收到分段错误,则说明您做错了。但是如果没有看到您的代码,我们将无能为力
-
仅供参考,您附加的内容是后缀,而不是前缀。
-
你如何决定在哪里注入整数?如果文件名不包含
.怎么办?如果它包含多次出现的.怎么办?你总是在字符串“data”之后插入_x(其中x是整数),还是总是在字符串“.log”之前,或者在第一个.之前,或者在最后一个.之前,或者其他地方?请明确点;计算机喜欢特异性。一旦你准确地定义了问题,通常解决方案就会变得非常清晰。
标签: c linux file file-handling