How to have a variable filename in the fprintf statement?

Status
Not open for further replies.

Old Nick

Advanced Member level 1
Joined
Sep 14, 2007
Messages
479
Helped
68
Reputation
136
Reaction score
18
Trophy points
1,298
Activity points
4,243
hi,

I'm writing software to rip data from a camera we designed, I need to take multiple images to manipulate in matlab. I am currently using fprintf to write files which is working fine.
But what I want to do is take 100-1000 frames and write each image to a file, incrementing the name of the file for every image.
Obviously a for loop would be ideal, but how do I have a variable filename in the fprintf statement.

Cheers for any help.

Nick
 

Re: fprintf

fprintf takes FILE pointer as an argument. That means that you will have to close previous file and than open a new one with fopen. fopen will taka a file name which a string, and can be constructed using sprintf.
 

    Old Nick

    Points: 2
    Helpful Answer Positive Rating
Re: fprintf

Cheers for that,

But what I need to know is how to change the name of an output file in a for loop.

I should have made it more clear that I already know how to close and open files, it is the renaming in a loop that I need to know.
 

Re: fprintf

I would use sprintf and the loop index (appended to the filename), something like:

Code:
#define MAX  100
#define BASE_FILE "myfile_"

char filename[255];
int  i;
FILE  *f;

for (i=0;i<MAX;i++) {
    sprintf(filename,"%s%03d",BASE_FILE,i);
    f = fopen(filename);
    if (f) {
        // write data
        fclose(f);
    }
}
Is this what you had in mind?
 

    Old Nick

    Points: 2
    Helpful Answer Positive Rating
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…