Interview Questions

How can I open files with names like ...

C Interview Questions and Answers


(Continued from previous question...)

How can I open files with names like ...

Q: How can I open files with names like ``file1'', ``file2'', ``file3'', etc., where the numeric part is controlled by a variable? Basically I want ``file%d'', like printf..

A: You want printf's close cousin sprintf, which ``prints'' to a string:
char filename[FILENAME_MAX];
sprintf(filename, "file%d", i);
fp = fopen(filename, "r");

(Continued on next question...)

Other Interview Questions