【问题标题】:How to append integer prefix to a file name in c?如何在c中将整数前缀附加到文件名?
【发布时间】: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


【解决方案1】:

我推荐使用asprintf() GNU 扩展:它可以在 Linux、Mac OS、FreeBSD 和其他平台上使用。

本质上,您将 char 指针初始化为 NULL,然后在您想要创建新字符串时将其传递给 asprintf。它将为其动态分配内存,并返回结果字符串的长度。如果发生错误,它将返回一个负值。您需要在 C 程序的开头使用以下内容来公开这些功能,

#define  _GNU_SOURCE   /* Needed on Linux for asprintf() to be exposed */
#include <stdlib.h>    /* For free(), exit() and EXIT_FAILURE */
#include <stdio.h>     /* For asprintf() and stderr */
#include <string.h>    /* For strerror() */
#include <errno.h>     /* For errno */

然后,在你的 main() 或其他地方,

    char *filename = NULL;
    if (asprintf(&filename, "/log/data_%d.log", num) < 0) {
        fprintf(stderr, "Cannot construct log file name: %s.\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    int fd = open(filename, O_CREAT | O_RDWR, 0666);
    if (fd == -1) {
        fprintf(stderr, "%s: Cannot create log file: %s.\n", filename, strerror(errno));
        free(filename);
        exit(EXIT_FAILURE);
    }

    /* Filename is no longer needed; free it */
    free(filename);
    filename = NULL;

【讨论】:

  • asprintf 是矫枉过正且不标准。
  • @Jabberwocky:与 snprintf() 不同,asprintf() 不受任意长度限制和假设的影响。在我看来,这使它更胜一筹。它也适用于我关心的所有系统,包括问题中标记的系统。
【解决方案2】:

你想要这样的东西:

#define filenametemplate "/log/data_%d.log"
...
int num; //This is the number I want to add to the file name    
...
char filename[100];
sprintf(filename, filenametemplate, num);
// now filename contains "/log/data123.log" (if num contains 123)
...

【讨论】:

  • snprintf(文件名,100,文件名模板,编号);
  • 或者更好snprintf (filename, sizeof(filename), filenametemplate, num);
猜你喜欢
  • 2021-05-27
  • 2020-07-25
  • 2022-11-11
  • 2022-11-16
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多