Text Files in MATLAB

📄 Text Files in MATLAB
MATLAB provides high-level and low-level functions to read from and write to text files efficiently.
MATLAB is developed by MathWorks.
🔹 What Is a Text File?
A text file stores data in plain text format, such as:
Numbers
Characters
Words
Lines of text
Example:
1️⃣ Reading Numeric Text Files — load()
Used when the text file contains only numeric data.
🔸 Example (data.txt)
🔸 MATLAB Code
Output
📌 Works only for numeric data.
2️⃣ Reading Text Files — fopen() + fscanf()
Used for formatted numeric data.
Output
3️⃣ Reading Line-by-Line — fgets()
Best for text content.
🔸 Example (info.txt)
🔸 MATLAB Code
Output
4️⃣ Reading Entire File — fileread()
Reads the whole text file at once.
📌 Simple and fast for small files.
5️⃣ Writing to a Text File — fprintf()
Output (report.txt)
6️⃣ Appending Data to a Text File
📌 'a' mode adds data without deleting existing content.
7️⃣ Writing Multiple Lines
8️⃣ Closing Files Properly
📌 Always close files to avoid memory leaks.
⚠️ Important Notes
'r'→ read mode'w'→ write (overwrites file)'a'→ appendAlways check file ID:
🎯 Interview Questions: Text Files in MATLAB
🔹 Q1. Which function opens a text file?
Answer: fopen()
🔹 Q2. Which function reads formatted data?
Answer: fscanf()
🔹 Q3. How do you read a full text file at once?
Answer: fileread()
🔹 Q4. Which function writes formatted text?
Answer: fprintf()
🔹 Q5. Difference between fgets() and fscanf()?
Answer:fgets() → reads one line as textfscanf() → reads formatted data
🔹 Q6. Why is fclose() important?
Answer:
To release file resources and avoid data corruption.
✅ Summary
Text files store plain data
MATLAB supports low-level file handling
fopen,fscanf,fgets,fprintfare key functionsEssential for logs, reports & custom data formats
