【问题标题】:Defining path using #define in C在 C 中使用#define 定义路径
【发布时间】:2012-03-13 18:54:56
【问题描述】:

我想定义这样的路径:

#define PATH /abc/xyz/lmn

此 PATH 是一个包含文件 foo1、foo2、foo3、... foo115 的目录。

如何在“open”调用中使用此#define 来打开 foo1, foo2, ... foo115 ?

我想基本上使用指令来做到这一点:

fd = open("/abc/xyz/lmn/foo1", O_RDONLY);

【问题讨论】:

    标签: c linux c-preprocessor


    【解决方案1】:
    #define PATH "/abc/xyz/lmn"
    
    int main (int argc, char **argv)
    {
       char file2open[256];
       int i;
    
       for (i = 1; i <= 115; i++)
       {
          sprintf (file2open, "%sfoo%d", PATH, i);
          fd = open (file2open, O_RDONLY)
          ......
          close (fd);
       }
    
    }
    

    【讨论】:

    • 既然你一直在使用 sprintf,那么 const char* 不是比定义的更好吗?
    • 我是老派(也许只是老了),#define 是我的习惯 - const char* 也一样好 :)
    • 下一个问题是,OP 真的希望这是一个编译时常量吗?这条路有可能改变吗?
    • 基于How can I use this #define in the "open" call to open foo1, foo2, ... foo115 ? 我说不
    【解决方案2】:
    #define PATH "/some/path/to/foo/files"
    
    for (int i = 0; 1 < SomeNumberOfFiles; i++)
    {
        char carray[256] = strcat(PATH, "foo");
        carray = strcat(carray, char(i));
        //Do something with the carray filename
    }
    

    我可能混入了一些 C++,抱歉。我尽量保持它为 C。

    【讨论】:

      【解决方案3】:

      例如,要打开foo42,您可以这样做:

      #define PATH  "/abc/xyz/lmn"
      fd = open(PATH "/foo42", O_RDONLY);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多