Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

A file with variable name in C

  1. Apr 11, 2010 #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.
     
  2. jcsd
  3. Apr 11, 2010 #2

    rcgldr

    User Avatar
    Homework Helper

    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.
     
  4. Apr 11, 2010 #3

    Mark44

    Staff: Mentor

    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.
     
  5. Apr 12, 2010 #4
    It works now, thanks. Previously I was trying with fopen("%s",stringname,"r") instead of
    just fopen(stringname,"r").
     
  6. Apr 12, 2010 #5

    Mark44

    Staff: Mentor

    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.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook