2012-03-13 41 views
3

語言中使用#define路我要定義這樣的路徑:定義用C

#define PATH /abc/xyz/lmn 

這條道路是具有文件foo1,foo2的,foo3 ... foo115目錄。

如何在「打開」調用中使用此#define打開foo1,foo2,... foo115?

我想基本上做到這一點使用的指令:

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

回答

9
#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

由於您使用的sprintf反正不會一個const char *比更好地界定? – 2012-03-13 19:07:00

+0

我是老學校(也許只是老),#define是我的習慣 - const char *是一樣好:) – KevinDTimm 2012-03-13 19:15:01

+0

接下來的問題是,OP是否真的希望這是一個編譯時常量?這條道路有可能改變嗎? – 2012-03-13 20:17:24

1
#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。

0

例如,打開foo42你可以這樣做:

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