Read text file julia: fscanf in Julia:

Hi everyone,

How can I read text file in the following way (matlab) in Julia?

or how can we use the similar function A = fscanf(fileID , formatSpec , sizeA ) in Julia?

Matlab

global ttn;
ttn= fopen('test.txt','r');
%--- read the input data:
n1=fscanf(ttn,'%d',1);
n2=fscanf(ttn,'%d',1);
n3=fscanf(ttn,'%d',1);
n4=fscanf(ttn,'%d',1);

test.txt:


4000 3000   178  30

Output:

n1=4000
n2=3000
n3=178
n4=30

See
https://docs.julialang.org/en/v1.1/stdlib/DelimitedFiles/#Delimited-Files-1

Sure it is a method, namely: I can convert text to vect: A; then n1=A[1], n2=A[2],… but not efficient for me

(n1,n2,n3,n4) = readdlm("test.txt", Int)

Also Strings · The Julia Language is useful read.

1 Like

@KajWiik , thanks a lot!

If txt file is much more complex, how can we read namely:

test.txt:

4000 3000   178  30
1 2 3 4
3 4 5 6
1.0 2.0
3.0 1.0
3.0 4.0 
4.0 5.0
1 2 3
4 5 6
4 5 6 

Output
n1=4000
n2=3000
n3=178
n4=30

A:
1 2 3 4
3 4 5 6

B:>

1.0 2.0
3.0 1.0
3.0 4.0
4.0 5.0

C
1 2 3
4 5 6
4 5 6

You follow the same method as described in the previous posts and process each line one at a time in a loop. Presumably the first numbers tell you how many lines of each type there are, so you write for loops with those lengths.

2 Likes