Defining path using #define in C

℡╲_俬逩灬. 提交于 2019-12-10 18:01:22

问题


I want to define a path like this:

#define PATH /abc/xyz/lmn

This PATH is a directory which has files foo1, foo2, foo3, ... foo115.

How can I use this #define in the "open" call to open foo1, foo2, ... foo115 ?

I want to basically do this using the directive:

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

回答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);
   }

}



回答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
}

I may have mixed in some C++, sorry. I tried to keep it as C as a I could.




回答3:


For example, to open foo42 you could do:

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


来源:https://stackoverflow.com/questions/9690265/defining-path-using-define-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!