2015-10-06 58 views
-3

所以我試圖編寫一個函數,它將打開一個不同的文件,具體取決於它何時被調用,但是當我檢查文件名,我試圖使用我得到一個奇怪的非acii字符,必須是一個問題與snprint。文件不可用的變量字符串名稱?

char name[20]; 
sprintf(name,"file_part%d", 6); //likely problem here. 
FILE *file=fopen(name,"r"); //this doesn't work 
printf("name is : %s", name); // and this prints a weird symbol on the terminal 
+1

由於您已經要求'printf'打印'name'的*地址*的第一個字節,所以您會得到一個奇怪的非ASCII字符。試試'printf(「name is:%s \ n」,name);''%c'將一個8位值打印爲一個字符。 '%s'打印一個字符串。 – lurker

+0

對不起,應該是s,但是文件仍然沒有打開,這是真正的問題,打印只是爲了調試。 – dcousina

+0

請解釋*不打開*。在fopen調用之後你檢查過'file'的值了嗎?它是否爲'NULL'?或者是什麼? – lurker

回答

2
printf("name is : %c", name); // and this prints a weird symbol on the terminal 

%c格式說明用於打印的字符,但name是由ASCII NUL終止字符數組(也稱爲C-風格字符串)。對於字符串,請使用%s,而不是%c

+0

對不起,我應該更清楚。這確實修復了acii字符,但它仍然無法正確打開文件。 – dcousina

+0

這是什麼意思?它是否打開文件不正確? –