필터 지우기
필터 지우기

How to store users input in a file?

조회 수: 4 (최근 30일)
Elsayed
Elsayed 2024년 5월 31일
댓글: Star Strider 2024년 5월 31일
Let's say I made a input asking for the users name and age, and wanted to say his input to a .txt file, I already know how to do that but my issue is how to keep that stored data if the script was ran again.
my code to store the users name and age:
name = input('What is your name? ','s');
age = input('How old are you? ');
fid = fopen('data.txt','w');
fprintf(fid,'%s is %i years old\n',name,age);
fclose(fid);

답변 (2개)

Star Strider
Star Strider 2024년 5월 31일
If you want to read the file, try something like this —
% name = input('What is your name? ','s');
% age = input('How old are you? ');
name = 'Rumpelstiltskin';
age = 142;
fid = fopen('data.txt','w');
fprintf(fid,'%s is %d years old\n',name,age);
fclose(fid);
type('data.txt')
Rumpelstiltskin is 142 years old
fid = fopen('data.txt','rt');
out = textscan(fid,'%s is %d years old\n');
fclose(fid);
out{1}
ans = 1x1 cell array
{'Rumpelstiltskin'}
out{2}
ans = int32 142
.
  댓글 수: 2
Elsayed
Elsayed 2024년 5월 31일
But this does basically what my code does? What I wanted to do is to save the input of the user and when the code was ran again, it makes a new line and adds the new users name. My code works fine, but if I was to run it again it would remove the data that was there.
Star Strider
Star Strider 2024년 5월 31일
I was not sure what you were asking.
One option would be to overwrite the file, and another would be to append to it.

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2024년 5월 31일
You want to open the file not in write mode ('w') but in append mode ('a'). See the description of the permission input argument on the documentation page for the fopen function. Since you're writing text data to the file you probably also want to add 't' to write in text mode, so 'at' instead of 'w'.
cd(tempdir)
fid = fopen('myfile.txt', 'wt'); % open for writing
fprintf(fid, "Hello world!\n");
fclose(fid);
type myfile.txt
Hello world!
fid = fopen('myfile.txt', 'at'); % open for appending
fprintf(fid, "This is a second line.\n");
fclose(fid);
type myfile.txt
Hello world! This is a second line.
fid = fopen('myfile.txt', 'wt'); % open for writing, discarding the existing contents
fprintf(fid, "Is this the third line? Guess not.");
fclose(fid);
type myfile.txt
Is this the third line? Guess not.
  댓글 수: 1
Elsayed
Elsayed 2024년 5월 31일
oh alright, thanks a lot steven, I get how it works now.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by