【问题标题】:Opening a numbered file in c在c中打开一个编号的文件
【发布时间】:2014-04-29 07:35:34
【问题描述】:

我遇到的问题只是打开一个文件,该文件具有基于输入的数字。 示例包括:

int main(int argc, char *argv[])
{
  int argument = atoi(argv[1]);
  FILE *fp;
  fp = fopen("/folder/item'argument'file", "r");
  //do stuff to the file
}

示例传递 4 将打开名为“item4file”的文件以供使用

我将如何解决这个问题?

衷心感谢您的任何帮助

【问题讨论】:

  • 你的例子有什么问题?

标签: c file char fopen


【解决方案1】:
int argument = atoi(argv[1]);  
FILE *fp;
char address[50]; // choose the size that suits your needs
sprintf (address, "/folder/item%dfile", argument);
fp = fopen(address, "r");

正如您所读到的from the reference,终止的空字符会自动附加到字符串。

然而,如果你想避免缓冲区溢出,你应该使用snprintf(显示在与上面相同的参考页面中),声明缓冲区的最大大小,以便输入不会溢出。

int argument = atoi(argv[1]);  
FILE *fp;
char address[50]; // choose the size that suits your needs
snprintf (address, 49, "/folder/item%dfile", argument); // 49 since we need one index for our null terminating character

【讨论】:

  • 完美运行。谢谢!这正是我想要的。再次感谢!
【解决方案2】:

使用sprintf()作为

char filename[50]
strcpy(filename,"/folder/item");
sprintf(str,"%s",argv[1]);
strcat(filename,str);
strcat(filename,"file");
fp=fopen(filename,"r");

【讨论】:

    【解决方案3】:

    使用snprintf 将整数转换为适合在文件路径名中使用的字符串。

    #include <stdio.h>
    #include <limits.h>
    
    int main(int argc, char *argv[])
    {
      int argument = atoi(argv[1]);
      char pathname[PATH_MAX];
      FILE *fp;
    
      snprintf(pathname, PATH_MAX, "/folder/item%dfile", argument);
      fp = fopen(pathname, "r");
      if (fp != NULL) {
        //do stuff to the file
      }
    }
    

    【讨论】:

      【解决方案4】:

      看看http://www.cplusplus.com/reference/cstdio/sprintf/。它允许您打印到字符串缓冲区。

      【讨论】:

        【解决方案5】:

        你可以这样使用它

        char filename[30];
        sprintf(filename, "/folder/item%dfile", argv[1]); 
        

        【讨论】:

          猜你喜欢
          • 2012-04-16
          • 2021-05-31
          • 1970-01-01
          • 2023-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多