Hi all,
I want to write a a simple C code to write a number of files each with a distinct file name...like file0, file1, file2, file3...
I tried to do it with memset and all, but didn't get very far :(
Can someone help me out please?
Thanks
dynamic file name in C?
Started by alirezan, Jan 13 2009 11:47 AM
4 replies to this topic
#1
Posted 13 January 2009 - 11:47 AM
|
|
|
#2
Posted 13 January 2009 - 12:02 PM
Can you show us the code you used? This should be fairly easy, but there may be some other issues involved.
#3
Posted 13 January 2009 - 01:11 PM
It's part of what I already have:
char str_fname[] = "./file";
char str_ext[] = ".txt";
int i;
for ( i=0; i<=2; i++)
{
strncat ( str_fname, (char*)i, 2 );
puts (str_fname);
strncat ( str_fname, str_ext, 20 );
puts (str_fname);
}
I can't attach the number i to it :( I keep getting segmentation fault.
Thanks
char str_fname[] = "./file";
char str_ext[] = ".txt";
int i;
for ( i=0; i<=2; i++)
{
strncat ( str_fname, (char*)i, 2 );
puts (str_fname);
strncat ( str_fname, str_ext, 20 );
puts (str_fname);
}
I can't attach the number i to it :( I keep getting segmentation fault.
Thanks
#4
Posted 13 January 2009 - 02:27 PM
Try using itoa(i) in your first strncat. Also realise that the results would be:
./file0.txt
./file0.txt1.txt
Also, your str_fname[] array isn't large enough to store the results of the strncat.
./file0.txt
./file0.txt1.txt
Also, your str_fname[] array isn't large enough to store the results of the strncat.
Edited by WingedPanther, 13 January 2009 - 02:28 PM.
add note.
#5
Posted 13 January 2009 - 03:37 PM
I know about itoa but the problem is, I can't use it... here's the message I get:
$ gcc -c ftest2.c
ftest2.c: In function `main':
ftest2.c:16: warning: passing arg 2 of `strncat' makes pointer from integer without a cast
$ gcc ftest2.o -o ftest2
ftest2.o(.text+0x60): In function `main':
: undefined reference to `itoa'
collect2: ld returned 1 exit status
I have included the following to my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
I believe the stdlib.h file is the one needed for itoa.
Here's what I have with itoa:
strncat ( str_fname, itoa(i), 2 );
Thanks
$ gcc -c ftest2.c
ftest2.c: In function `main':
ftest2.c:16: warning: passing arg 2 of `strncat' makes pointer from integer without a cast
$ gcc ftest2.o -o ftest2
ftest2.o(.text+0x60): In function `main':
: undefined reference to `itoa'
collect2: ld returned 1 exit status
I have included the following to my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
I believe the stdlib.h file is the one needed for itoa.
Here's what I have with itoa:
strncat ( str_fname, itoa(i), 2 );
Thanks


Sign In
Create Account


Back to top









