Jump to content

dynamic file name in C?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
alirezan

alirezan

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
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

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Can you show us the code you used? This should be fairly easy, but there may be some other issues involved.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
alirezan

alirezan

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
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

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
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.

Edited by WingedPanther, 13 January 2009 - 02:28 PM.
add note.

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
alirezan

alirezan

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
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