zaplec
zaplec

Reputation: 1819

How to make a increasing numbers after filenames in C?

I have a little problem. I need to do some little operations on quite many files in one little program. So far I have decided to operate them in a single loop where I just change the number after the name. The files are all named TFxx.txt where xx is increasing number from 1 to 80. So how can I open them all in a single loop one after one? I have tried this:

for(i=1; i<=80; i++) {
   char name[8] = "TF"+i+".txt";
   FILE = open(name, r);
   /* Do something */
  }

As you can see the second line would be working in python but not in C. I have tried to do similiar running numbering with C to this program, but I haven't found out yet how to do that. The format doesn't need to be as it is on the second line, but I'd like to have some advice of how can I solve this problem. All I need to do is just be able to open many files and do same operations to them.

Upvotes: 0

Views: 1074

Answers (5)

tangrs
tangrs

Reputation: 9940

And shouldn't char name[32] be outside the for loop?

Upvotes: 0

ShinTakezou
ShinTakezou

Reputation: 9681

Let us suppose yours is just pseudocode; otherwise the problem is not only

char name[8] = "TF"+i+".txt";

where you use a sum to concatenate strings and convert an integer into string... (this is reasonable on some languages, absolutely not in C, where the + is just a sum between numbers)... but also FILE = open... is problematic...

char name[BUFLEN];
sprintf(name, "TF%d.txt", i);

would fill your name (snprintf(name, BUFLEN, "TF%d.txt") could be better, but it is C99, while the other is C89 too).

Files can be opened using something like FILE *fh = fopen(name, "r") for reading.

Upvotes: 1

Daniel Băluţă
Daniel Băluţă

Reputation: 1275

You can use sprintf as follows:

for(i=0; i<=80; i++) {
   char name[32];
   memset(name, 0, sizeof(name));
   FILE *fp;
   sprintf(name, "TF%d.txt", i);
   fp = fopen(name, "r");
   /* Do something */
  }

Upvotes: 5

stacker
stacker

Reputation: 68992

In addition to Daniels answer I would like to add that char name[8] should be little bigger to hold the terminating '\0' i.g. char name[20];

and FILE = open(name,r); should be FILE * fp = fopen(name,"r");

Upvotes: 1

TheMorph
TheMorph

Reputation: 572

Maybe I am wrong, but just use fopen instead of open and write "r" instead of r?

FILE = fopen(name, "r");

Upvotes: 0

Related Questions