简体   繁体   中英

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.

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 */
  }

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

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

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.

也许我错了,但是只使用fopen而不是open并用“ r”代替r?

FILE = fopen(name, "r");

并且char name[32]是否不应该位于for循环之外?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM