This is my code. I need create 10 files with this format:
0.txt
1.txt
…
But I can’t do it, the result is different. Can anyone help?
#include <stdlib.h>
#include <string.h>
char* direccion(char *dirD,int number){
char buffer[100];
char *n;
char *q;
char* formato=".txt";
sprintf(buffer, "%i", number);
n= strcat(dirD,buffer);
q= strcat(n,formato);
return q;
}
int main(){
int u;
int number= 0;
int t= 0;
char* q = "e:/c9/";
for(t=0; t< 10 ; t++){
char* dir = direccion(q,number);
if(fopen(dir,"w")){
fopen(dir,"w");
u=1;
}
else{
u=0;
printf("Error\n");
}
number++;
}
return 0;
}
Thanks !
Problem No 1. is:
The variable q is a string literal. However, in the function
direccion(), you pass it as the first argument tostrcat(), which tries to modify it — BOOM, a segfault. Solution:Problem #2 is as @Charlie Martin pointed out is that you return a
staticallyautomatically allocated local string, which is invalid after thedireccion()function returns. Maybein this case; don’t forget to free it after use.
Edit: seems you don’t even ask about this. You can create a file using the
open()system call (function):Of course substitute the actual file mode you want for 0644 (but don’t make the file executable unless it contains a program to be executed).
Edit 2: I didn’t even catch this one… So, in the for loop, you want to reset the base filename over and over:
etc.