2014-02-19 137 views
0

我有30個文件,我想在C字符串聯

phantom_atn_1.bin phantom_atn_2.bin 開... phantom_atn_30.bin

我嘗試以下,但它不工作:

#include <math.h> 
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 

char filename[100],filename1[100],extension1[100]; 
int fileNum,frameNum; 


main() 
{ 
    printf("Test1\n"); 
    frameNum=30; 

    strcpy (extension1, ".bin"); 

    for (fileNum=1;fileNum<frameNum+1;fileNum++) 
    { 
     printf("Test2\n"); 
     strcpy (filename1, "phantom_atn_"); 
     printf("Test3\n"); 
     printf(filename1); 
     printf("\n"); 
     printf(filename,"%d", fileNum); 
     printf("Test5\n"); 
     sprintf(filename,"%d", fileNum); 
     printf("Test6\n"); 
     strcat(filename1,extension1);  
     printf("Test7\n"); 
     printf(filename); 
     printf("Test8\n"); 
     printf(filename); 
     image1=fopen(filename,"rb"); 
    } 
}; 

任何幫助將不勝感激。

+2

如何'不work' ??? – herohuyongtao

+0

請正確縮進您的代碼。 –

回答

1

希望這將工作:

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 

char filename[100]; 
int fileNum,frameNum; 


main() 
{ 
    FILE *fp[30]; 
    char *extension1 = ".bin"; 
    frameNum=30; 
    for (fileNum=1;fileNum<frameNum+1;fileNum++) 
    { 
    sprintf(filename, "phantom_atn_%d%s", fileNum, extension1); 
    printf("%s\n", filename); 
    //I have opened file in write mode here                                                                     
    fp[fileNum] = fopen(filename, "w"); 
    //now you can write anything in file pointer using below code                                                               
    fprintf(fp[fileNum], "%d", fileNum); 
    } 
} 
+0

它運作良好。非常感謝您的幫助。真的很感激它! :) – user3326508

6

爲什麼不簡單地使用例如snprintf

snprintf(filename, sizeof(filename), "phantom_atn_%d.bin", fileNum); 

_snprintf在Windows上)

+0

我正在使用Linux。 – user3326508