2012年4月14日 星期六

[C] fopen 檔案路徑


FILE * fopen (const char * filename, const char * mode);
FILE * fp = fopen("input.txt", "r");
是最常見的方式

但若需要以變數產生檔名,一般用法行不通
FILE *fp;
const char filename[9] = "input.txt";
fp = fopen(filename, "r");
則 fp 會回傳 NULL

正確用法為呼叫

int sprintf ( char * str, const char * format, ... );


FILE *fp;
char filename[9];
int i;

for(i = 0; i < 5; i++){
sprintf(filename, "input%d.txt", i);
fp = fopen(filename, "r");
}
如此檔名才能被fopen吃進去

沒有留言:

張貼留言