create and name .txt file with fopen
124 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jonas K
el 22 de Jun. de 2017
Comentada: Star Strider
el 22 de Jun. de 2017
Hello, I have the following piece of code:
num_lights = 3;
light_direction = [1, 2, 3; 4, 5, 6; 7, 8, 9];
fileID = fopen('test_name.txt','w');
fprintf(fileID, '%i \n', num_lights);
fprintf(fileID, '%f %f %f \n', light_direction);
fclose(fileID);
The problem is, I don't want a fixed name for my file. It should look somewhat like this:
fileID = fopen('test_name', xyz, '.txt','w');
xyz would be a %s.tring that is defined earlier. What is my mistake. The documentation for fopen doesn't seem to include more complex names. And I don't want to use a rename function since this wouldn't be proper programming (I was told...)
Thanks for your help! J
0 comentarios
Respuesta aceptada
Star Strider
el 22 de Jun. de 2017
Assuming ‘xyz’ is a string, this should do what you want:
xyz = ...; % Define ‘xyz’
fileID = fopen(sprintf('test_name%s.txt', xyz) ,'w');
If it is numeric, then replace ‘%s’ with ‘%d’ or whatever format descriptor is most appropriate.
2 comentarios
Star Strider
el 22 de Jun. de 2017
My pleasure!
Strings are actually character arrays, and are designated with single quotes. The quotes themselves are not actually parts of the character array, they just designate it as such. (To make strings even more complicated, there is now a string (link) variable type that first appeared in R2016b. I mention that because ‘string’ is now a function so using it as a variable name will ‘overshadow’ the function, making the function unusable.)
No worries — none of us were born knowing any of this. Some of us just have a bit more experience with it by now.
Más respuestas (0)
Ver también
Categorías
Más información sobre Low-Level File I/O en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!