Challenge - 5 Problems
Text File Writing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this fprintf code?
Consider the following MATLAB code that writes formatted text to a file. What will be the content of the file after running this code?
MATLAB
fid = fopen('output.txt', 'w'); fprintf(fid, 'Value: %d\n', 42); fclose(fid); file_content = fileread('output.txt'); disp(file_content);
Attempts:
2 left
💡 Hint
Remember that fprintf with '%d' replaces the placeholder with the integer value and '\n' adds a new line.
✗ Incorrect
The fprintf function writes 'Value: 42' followed by a newline character to the file. The fileread reads the file content including the newline, so the displayed content includes the line break.
❓ Predict Output
intermediate2:00remaining
What does writetable write to the file?
Given this MATLAB code, what will be the content of 'data.csv' after execution?
MATLAB
T = table([1;2;3], {'A';'B';'C'}, 'VariableNames', {'ID', 'Letter'}); writetable(T, 'data.csv'); content = fileread('data.csv'); disp(content);
Attempts:
2 left
💡 Hint
writetable writes variable names as headers by default and separates values with commas in CSV format.
✗ Incorrect
The writetable function writes the table with headers separated by commas and each row on a new line, so the file content includes the header line 'ID,Letter' followed by the data rows.
🔧 Debug
advanced2:00remaining
Why does this fprintf code produce an error?
Examine the code below. Why does it cause an error when run?
MATLAB
fid = fopen('test.txt', 'w'); fprintf(fid, 'Number: %d %f\n', 5); fclose(fid);
Attempts:
2 left
💡 Hint
Check how many values fprintf expects based on the format string placeholders.
✗ Incorrect
The format string '%d %f\n' requires two values, but only one (5) is provided. This mismatch causes fprintf to error.
📝 Syntax
advanced2:00remaining
Which option correctly writes a table without row names?
You want to write a table to a CSV file without including row names. Which code does this correctly?
MATLAB
T = table([10;20], {'X';'Y'}, 'VariableNames', {'Num', 'Char'});
Attempts:
2 left
💡 Hint
Check the exact parameter name for controlling row names in writetable.
✗ Incorrect
The correct parameter to exclude row names is 'WriteRowNames' set to false. Other options use incorrect parameter names or values.
🚀 Application
expert2:00remaining
How many lines are written by this fprintf loop?
This MATLAB code writes lines to a file. How many lines will the file contain after running?
MATLAB
fid = fopen('log.txt', 'w'); for i = 1:5 fprintf(fid, 'Line %d\n', i); end fclose(fid); content = fileread('log.txt'); lines = count(content, '\n');
Attempts:
2 left
💡 Hint
Each fprintf call writes one line ending with '\n'. Count how many times the loop runs.
✗ Incorrect
The loop runs 5 times, each writing one line with a newline character, so the file has 5 lines.