How to Open a File with a Variable Name in C?

  • Thread starter Thread starter Lojzek
  • Start date Start date
  • Tags Tags
    File Variable
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 7K views
Lojzek
Messages
246
Reaction score
1
How to open a file with a name that is not defined in advance, but
is entered after the program is executed?
I am using fopen function, but it seems that it's argument must be
a fixed string, not a variable.
 
Physics news on Phys.org
fopen uses a pointer to a variable length string terminated with a zero, sometimes called a "C" string (as opposed to a fixed length string that includes size information, usually called a "P" (Pascal) string). You just need to input a string from the user. You can also use an array, since the array name is treated similar to a pointer in C.
 
I'm pretty sure that the filename parameter doesn't have to be a string literal, so you can get the filename at run time. What the const char * filename parameter means is that fopen won't change the string that's passed to it.
 
It works now, thanks. Previously I was trying with fopen("%s",stringname,"r") instead of
just fopen(stringname,"r").
 
It looks like you confused printf with fopen, at least as far as the format string in printf is concerned. When you use standard library functions, make sure you understand what the parameters are used for, and that you use the right number of them.