Opening file in a for loop with a changing integer in title

I am trying to convert a series of files into arrays. Each file is named molx.m where x is a number between 1-180. I am successfully able to convert one file to a matrix using the following code to open a file:

1
2
3
4
5
	FILE* fp = fopen("mol0.m", "r");
	fscanf(fp, "%i\n", &x);
	printf("X=%i\n", x);

        ...


However I now wish to create a for loop that will work through the array conversion routine for each file that I have. This means that on each run through the for loop I wish to open the file mol"y".m where y is a variable between 0-180. My problem is that I do not know how to insert the y into the filename. My initial thought was to try something akin to how you would use printf:

1
2
3
4
	FILE* fp = fopen(("mol%i.m", y) , "r");
	fscanf(fp, "%i\n", &x);
	printf("X=%i\n", x);
        ...


However on compilation this produces
"error: invalid conversion from ‘int’ to ‘const char*’
error: initializing argument 1 of ‘FILE* fopen(const char*, const char*)’"

I have tried changing the type of y to a char and get the same problem and char* which compiles but I get a segmentation fault when I try to run the program. I feel like I am missing something obvious here as it does not seem like a very difficult problem, any help would be appreciated. Thanks.
Last edited on
sprintf will do what you want. itoa will also do it but it is not standard.
Thanks for the help, if anyone is interested the code I used was:
1
2
3
4
5
6
7
8
9
10
	for(y=0; y<188; y++){

		sprintf(molname, "mol%i.m", y);
		printf("%s\n", molname);

		FILE* fp = fopen(molname, "r");
		fscanf(fp, "%i\n", &x);
		printf("X=%i\n", x);

                ...


Thanks again.
Topic archived. No new replies allowed.