Create a file with 20 lines of text and name it linestxt Wri

Create a file with 20 lines of text and name it \"lines.txt\". Write a program to read this as file \"lines.txt\" and write the text to a new file, \"numbered_lines.txt\", that will also have line numbers at the beginning of each line.

Example:

Input file: \"lines.txt\"

Line one

Line two

Expected output file:

1 Line one

2 Line two

Solution

MATLAB CODE:

fileID = fopen(\'lines.txt\',\'r\'); % Open lines.txt file in reading mode ( r mode)

formatSpec = \'%f\'; % I have stored lines.txt with floating numbers so I used this as formatspace

sizeA = [1 Inf];

A=fscanf(fileID,formatSpec,sizeA); % assigning values in the file into a variable A.

fclose(fileID); %closing file

fileID = fopen(\'numbered_lines.txt\',\'w\'); % Opening file in W mode

fprintf(fileID,\'%4.4f\ \',A); % writing into file

fclose(fileID);% closing file

lines.txt file

81.4724
90.5792
12.6987
91.3376
63.2359
9.7540
27.8498
54.6882
95.7507
96.4889
15.7613
97.0593
95.7167
48.5376
80.0280
14.1886
42.1761
91.5736
79.2207
95.9492

Create a file with 20 lines of text and name it \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site