Read array from .txt data - arrays

I would like to read an array from a .txt file in Fortran. I tried it with the following code:
PROGRAM test_performance
IMPLICIT NONE
DOUBLE PRECISION, DIMENSION(:), ALLOCATABLE :: ARRAYONE
OPEN(UNIT=20,FILE='testfile.txt',STATUS='OLD', ACTION='READ')
READ (20,*) ARRAYONE
print *, 'here I am!'
CLOSE(UNIT=20)
write(*,*)ARRAYONE
OPEN(UNIT=30,FILE='TEXTFILE.txt', STATUS='REPLACE', ACTION='WRITE')
WRITE(30,*)ARRAYONE
END PROGRAM test_performance
There is no error when I compile it. The point is that the array ARRAYONE as well as the file TEXTFILE.txt are empty.
The file testfile.txt Looks like this:
1 2 3 4 5 6 7 8 9 10 11
I have got a book in front of me according to which this should actually work. What puzzles me is the fact that if I put just one number in the input file, i.e., 1, and I want to write it on an integer, there is no problem and everything works fine :o!

In the vainglorious pursuit of rep, and with the noble intention that this question get an answer
You can't automatically allocate an array in a read statement, the rules forbid it (or, if you prefer, do not make allowance for it). You could either:
allocate the array to some size that you expect to be large enough, populate it with a guard value unlikely to be found in your inputs, and then read the data you have into the first n elements; or
read the data, figure out how many elements there are, allocate the array to that size, pass the data to the array; you could do this in two passes over the input file (one to determine the contents, the second to read it) or you could get clever and read the data into, say, a large string and parse it to find out how many numbers it contains (so simple it's scarcely worthy of the name 'parsing').
There are other ways, I'm sure you can think of some.

Related

How to read in data from a file when not knowing the size of the file and datatypes aren't consistently ordered

I am trying to read a file that is filled with ints and strings. The file starts with 1 string followed by 2 ints (this is always the case). Then the rest of the data in the file is strings (this can range from 1 string to hundreds). I want to store the first string into a variable and the two ints into their own separate variable and the strings into an array.
I initially tried using fscanf but sense the file can contain an arbitrary number of strings after the 2 ints. I figured this would not work. I am now thinking that I need to somehow parse the data / tokenizing the data. Any ideas would be appreciated.
DATA FILE
S11FREE
2
0
(A,B)(C,D)
(E,F)(G,H)
(I,J)(K,L)
(M,N)(O,P)
...
...
...
...
(...) as in more strings in the same format
You can follow these steps:
read in the string, any way you are comfortable with
read in the integers, dito
read in the rest of the file, but ...
either
ignore it, apart from the size of the strings, which you accumulate
use the knowledge of the size to malloc() a suitably sized memory part (hopefully not beyond your total available memory
read in the file again and store the strings into consecutive parts of the reserved memory
keep track of which string you store where (e.g. by storing the locations separately) or insert \0 between them (do not forget to calculate them into the total size)
or
read the input into a growing data structure like e.g. a linked list
process it from there
or
temporarily store into a linked list
when done you know the total size
then create a memory with malloc() and move the data there, while deleting the linked list
or the idea you mention in a later comment, using realloc.

Problem using printf while copying numbers from a file to an array

I have this problem with my code. Im was copying some numbers from a file i had opened into an array using a for loop. And at the same time, i put a printf statement after the fscanf statement to see whether the value i wanted actually entered the arr. This works fine except that it puts an extra number at the end of the array when it's done. i don't understand why this happens. At first, i thought that I was using a wrong count of the number of elements in the file or that i had messed up while using malloc but those are completely fine. Can anyone pls tell what wrong. I can't share the code until a specific date cause i am a student and it would be considered cheating.
EDIT: Below is a link to a segment of what is happening in the code. THE LANGUAGE IS C. The code is meant to read the numbers 1
7
5
6
8
3
9
4
2
10
from a file a made but instead it always reads 1
7
5
6
8
3
9
4
2
10
1
EDIT: In the function declaration i meant char* file_name not int char*filename.
the image but i cant embed yet so a link
There are multiple problems in your code:
there is a syntax error in the function prototype: int char* filename should just be const char *filename.
you do not test the return value of fopen(). You will have undefined behavior if the program cannot open the file.
you do not test if fscanf() succeeds at converting the file contents as an integer. You should verify the it returns 1 and handle the error if it does not.
It is quite likely that the number of values passed to the function exceeds the number of values actually present in the file. In this case, the contents of the destination array is not changed beyond the last value read and printf outputs whatever happens to be present there.
You should post the whole program as text in your question for a more complete analysis and potential corrections.

Reading data from file into a two-dimensional array

I'm totally new to fortran and also programming (minor experience). I have a difficulty in writing a code for the following.
I need to store data in a two-dimension array using the data from two input files
Then I need to determine the size of the two files
Then need to select the variables from both dimensions for a specific value of one variable
and then calculate the average
Finally write the results to a new data file.
Eg:
There is two radiosonde data files with pressure, height, temperature, dew point values with different data sizes
Need to get the mean values for height, temperature and dew point, at specific pressures of 1000, 850 and 500 (both files have these records) and write to a new file.
I have gone through a couple of books but couldn’t grasp the exact thing I’m looking for. Can anyone of you give me some insight to the coding? I’m really thankful to you guys.
Your code will look something like this:
program main
implicit none
real::height(100)
integer::i
open(unit=16, file='height.dat')
do i = 1, 100
read(16, *) height(i)
enddo
close(16)
open(unit=16, file='mean_height.dat')
write(16, *) sum(height)/100
close(16)
end program
This assumes there is a file named height.dat with one height value per line, 100 lines total.
It reads the 100 heights in, then writes out the mean height to a file mean_height.dat.
You will obviously have to signficantly modify this.
For example, you won't know there are 100 lines in the file, so you will need to use an allocatable array for the values you read in:
program main
implicit none
real,allocatable::height(:)
integer::i, N
!Code that figures out how many lines there are
!...
allocate(height(N))
open(unit=16, file='height.dat')
do i = 1, N
This should get you started... Ideally you could start with a simpler input file than what you describe to learn the basics.

How to save a 2-Dimensional array to a file in C?

I am an beginner C programmer and I am currently working on a project to implement viola jones object detection algorithm using C. I would like to know how I would be able to store data in a 2-Dimensional array to a file that can be easily ported and accessed by different program files(e.g. main.c, header_file.h etc.)
Thank you in advance.
There's not quite enough detail to be sure what you're looking for, but the basic structure of what you want to do is going to look something like this:
open file.csv for writing
for(iterate through one dimension of the array using i)
{
for(iterate through the other dimension of the array using j)
{
fprintf(yourfilehandle,"%d,",yourvalue[i][j]);
}
fprintf(yourfilehandle,"\n");
}
close your file
As has been suggested by others, this will leave you with a .CSV file, which is a pretty good choice, as it's easy to read in and parse, and you can open your file in Notepad or Excel and view it no problems.
This is assuming you really meant to do this with C file I/O, which is a perfectly valid way of doing things, some just feel it's a bit dated.
Note this leaves an extraneous comma at the end of the line. If that bugs you it's easy enough to do the pre and post conditions to only get commas where you want. Hint: it involves printing the comma before the entry inside the second for loop, reducing the number of entries you iterate over for the interior for loop, and printing out the first and last case of each row special, immediately before and after the inner for loop, respectively. Harder to explain that to do, probably.
Here is a reference for C-style file I/O, and here is a tutorial.
Without knowing anything about what type of data you're storing, I would say to store this as a matrix. You'll need to choose a delimiter to separate your elements (tab or space are common choices, aka 'tsv' and 'csv', respectively) and then something to mark the end of a row (new line is a good choice here).
So your saved file might look something like:
10 162 1 5
7 1 4 12
9 2 2 0
You can also define your format as having some metadata in the first line -- the number of rows and columns may be useful if you want to pre-allocate memory, along with other information like character encoding. Start simple and add as necessary!

Reading a list of numbers separated by comma into an array in C

I have a file of the following form
-1,1.2
0.3,1.5
Basically a list of vectors, where the dimension of the vectors is known but the number of vectors isn't. I need to read each vector into an array. In other words I need to turn
-1,1.2
into an array of doubles so that vector[0] == -1 , vector[1] == 1.2
I'm really not sure how to start.
There's three parts to the problem:
Getting access to the data in the file, i.e. opening it
Reading the data in the file
Tidying up, i.e. closing the file
The first and last part is covered in this tutorial as well as a couple of other things.
The middle bit can be done using formatted input, here's a example. As long as the input is well formatted, i.e. it is in the format you expect, then this will work OK. If the file has formatting errors in then this becomes trickier and you need to parse the file for formatting errors before converting the data.

Resources