opening data files with variable names

Anything that doesn't fit elsewhere.
Post Reply
Posts: 2
Joined: Tue May 23, 2006 6:46 pm
Location: Cambridge, England

opening data files with variable names

Post by rita »


Is there a way to open a file whose name is determined by a variable that I set? i.e., i have many data files that have this naming scheme:




and in every simulation i need to change the path number that is used

so instead of changing the path numbers in every data file i open in my hoc file, I would like to just set a variable to do this, something like:

i = 2

objectvar glutfile
glutfile = new File()

objectvar gabafile
gabafile = new File()

Is there a way to do this? It would be extremely convenient..thanks!


Site Admin
Posts: 5770
Joined: Wed May 18, 2005 4:50 pm
Location: Yale University School of Medicine

Post by ted »

>>>> Hint: when reading the Programmer's Reference, every time you see an
example that involves an explicit string, such as
fobj = new File("filename")
a strdef can be substituted for the explicit string, e.g.
strdef foo
foo = "fap"
fobj = new File(foo) // opens file called "fap"

So the solution to your current problem is: use sprint to print the file name to a string.

Code: Select all

objref datafile
strdef basename, extension, filename
extension = "dat"
basename = "whatsis"

for ii = first,last {
  sprint(filename, "%s%d.%s", basename, ii, extension)
  datafile = new File(filename)
  // etc.
Read about File class here ... /file.html
Read about sprint here ... tml#sprint
Read about format strings here ... tml#printf

Posts: 2
Joined: Tue May 23, 2006 6:46 pm
Location: Cambridge, England

Post by rita »

Thanks for your prompt response! Its much easier to run simulations now and my eyes don't get glazed over from changing numbers!

Post Reply