create and name .txt file with fopen
조회 수: 124 (최근 30일)
이전 댓글 표시
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
채택된 답변
Star Strider
2017년 6월 22일
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
Star Strider
2017년 6월 22일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Low-Level File I/O에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!