file-io,fortran,gfortran , Accessing open files globally in Fortran

Accessing open files globally in Fortran


Tag: file-io,fortran,gfortran

Is there any means to accessing (reading, writing to) files that are opened in some other source code by just passing the unit number?


Yes, that is possible (for both reading and writing). Here is a short example:

module test_mod

  subroutine myWrite( uFile )
    implicit none
    integer, intent(in) :: uFile

    write(uFile, *) 'Hello world'
  end subroutine
end module

program test
  use test_mod
  implicit none
  integer :: uFile, stat

  open(newunit=uFile, file='test.txt', status='replace', &
       action='write', iostat=stat)
  if( return

  call myWrite( uFile )
  close (uFile)
end program

$ cat test.txt 
 Hello world


Unclassifiable statement at (1) in Fortran

I am pretty new to to fortran and I don't really know why am I getting this error. integrand(i)=inte(x(i),beta,r2,r1) 1 Error: Unclassifiable statement at (1) calka11.f95:97.6: I have made all the variables into a module file and then call them using use and when I am getting those variables into...

Java FileOutputStream Created file Not unlocking

Currently am facing a problem with FileOutputStream in my code used FileOutputStream for creating file in my disk .Once file created there is no way for opening , deleting or moving file from its location ,getting error message already locked by other user When stopped web server it working properly...

Open,Close ObjectOuputStream but still want to Append the serialized objects tot the end ?

I am obliged to open a ObjectOutputStream, then write an object an finally close the stream. I do that multiple times using the following code : // try-with-statement is very practical try(FileOutputStream fos = new FileOutputStream("G.txt") ; ObjectOutputStream oos = new ObjectOutputStream(fos);){ oos.writeObject(v); } catch (IOException e) { e.printStackTrace(); }...

How can I get the location of a user's Documents directory?

I want to be able to write a string to a text file on any computer. For example string line = "Sample text to write" File.WriteAllText(@"C:\Users\Rolex James\Documents\sample.txt" , line); On another system this path would be different, is there a way of writing it such that you don't have to...

How to handle the File hand-off from windows in a python program

I want to set up my python program to process all pdfs that are opened on my system, and then hand the processed pdf off to a standard reader. So I register my program with windows as the default handler for .pdf files and windows presumably will run my program...

java.nio.file.NoSuchFileException: why nio not creating file [closed]

I am using java.nio.file package and tried to create file with the following code. private static void printReport(String filename, String str)throws Exception{ ErrorCheck ec = new ErrorCheck(); String fileName = "/var/Emails_log/"+filename; Path filePath = Paths.get(fileName); File file = new File(fileName); final BufferedWriter out = Files.newBufferedWriter(filePath, StandardCharsets.UTF_8, StandardOpenOption.APPEND); try{ final Path...

FORTRAN unformatted file write by each process

In my parallel program, there was a big matrix. Each process computed and stored a part of it. Then the program wrote the matrix to a file by letting each process wrote its own part of the matrix in the correct order. The output file is in "unformatted" form. But...

Using move_alloc in a derived type

I have written a derived type that stores a multidimensional array. The array will be read from a file to an array b. I then want to transfer b to the derived type Space using member a. The advantage for mvalloc is not having to allocate two large arrays which...

Haskell return lazy string from file IO

Here I'm back again with a (for me) really strange behaviour of my newest masterpiece... This code should read a file, but it doesn't: readCsvContents :: String -> IO ( String ) readCsvContents fileName = do withFile fileName ReadMode (\handle -> do contents <- hGetContents handle return contents ) main...

Are the LAPACK routines thread safe?

I am a novice using the LAPACK routines, so I don't deeply know them, and I want to use them in parallelized loops (openmp). I use Ubuntu 14.04LTS and have LAPACK installed using my package manager. The version installed is: liblapack3 3.5.0-2ubuntu1 Library of linear algebra routines 3 - shared...

Fortran: makefile error

I have a fortran main program called solidsolver.f90, and a module called read_mesh.f90. The module contains two subroutines and is used in the main program. I can compile them manually but not with a makefile. My makefile is named makefile.makefile, and it gives me an error: make: *** No targets...

Precision not respected

I use Visual Studio (2010 SP1) with Fortran IMSL (2011) and I can't get the right precision for my reals: program prova use, intrinsic :: iso_fortran_env implicit none integer, parameter :: ikind=selected_real_kind(p=8, r=99) real(kind=ikind) :: a=0.79 real(real64) :: b=0.79 real(kind=16) :: c=0.79 real(8) :: d=0.79 print *, a print *,...

Batch file to conditionally execute ifortvars.bat

I am using a make.bat file to compile my Fortran code. To compile using the ifort command, I first need to initialize the compiler by executing ifortvarsbat intel64 command where I had to setup the path variable. This works fine, however, the path keeps increasing in size and says command...

Troubles reading a single character from a text file

I'm writing an "app" that takes in time input from the user and stores the hours and the minutes separately for each day in a text file (giving a result that looks like: day 1: 8h 45min day 2: 8h 43min ... ) the idea behind it is to use...

Using allocatable/assumed-size arrays with namelist read write

I am using VS2012 and Intel Visual Fortran 2015. According to, it is now allowed to use allocatable and assumed-size arrays with namelist read and write; however, I am still getting the error "A namelist-group-object must not be an assumed-size array". example code: subroutine writeGrid(fname, grid) character*(*) :: fname...

Hadoop map reduce Extract specific columns from csv file in csv format

I am new to hadoop and working on a big data project where I have to clean and filter given csv file. like if given csv file has 200 columns then I need to select only 20 specific columns (so called data filtering) as a output for further operation. also...

Fortran derived type in common: initialization?

I got troubles with this common: COMMON /REDCOM/ DPREC,NITMA,INDIC,NBERR,NCAR,KMOTLU, & REDVAR,MOCDER(2) COMMON /REDCO1/ CTEXT C type(double_st) :: DPREC INTEGER :: NITMA,INDIC,NBERR,NCAR,KMOTLU,REDVAR,MOCDER CHARACTER(72) :: CTEXT CHARACTER(4) :: CTEXT4 C EQUIVALENCE (CTEXT,CTEXT4) The double_st derived type is: type double_st sequence real(kind(0.d0)) :: x,y,z integer :: acc = -1 end type double_st Trying...

error: 'x' argument pf 'dtime' intrinsic at <1> must be of kind 4

My understanding of programming is very limited so I hope I am making sense. I made a change to a fixed variable in a program (the program is called NAFnoise; I was using the .exe but it came with the source code and I made the change there). The program...

Linux: Using split on limited space

I have a huge file on a linux machine. The file is ~20GB and the space on my box is ~25GB. I want to split the file into ~100mb parts. I know theres a 'split' command but that keeps the original file. I don't have enough space to keep the...

unformatted output with wild card in Fortran

I've searched for a long time before I ask: I need to output a lot of unformatted files in Fortran to Ensight. I want to name them with geo.000000, geo.000001 ... geo.0001000. Here is how I deal with wild card: character(54) :: filename, temp character(80) :: buffer write(temp,'(i6.6)') step filename...

Java: Create Directory with Loop

I make a program that create a directory on desktop with the name of world but i need 10 more directories in this world directory with the name of world1,world2 etc with the help of loop i enter loop but it doesn't create directories inside world. Code: public class A...

Can I declare only specific elements of an array as constant? (C/C++/Fortran)

Scenario: I pass e.g. a 2D matrix as argument in a function and I would like to be able to read and change all the elements, BUT I would like to prevent any accidental writting in let's say the last column. So I would like somehow to tell the compiler...

Ambiguous reference to variable

So I am doing 2 modules which are linking to the main program. The first one has all the variables defined in it and the second one is with the functions. Module1: module zmienne implicit none integer, parameter :: ngauss = 8 integer, parameter :: out_unit=1000 integer, parameter :: out_unit1=1001...

How to call Fortran routine with unit number argument from C

If I have a Fortran subroutine which takes a Fortran IO Unit as one of its parameters (for printing debug information to), and this function is compiled into a shared library, how do I correctly call this function from C? ! An example subroutine that I want to call from...

How can I implement BCD in Fortran?

Not sure if the title of my question makes sense, so bear with me. I'd like to find a system for representing single digit numbers with as few bits as possible. There is a method called "Densely packed decimal" ( which would be my ideal solution, but I wouldn't even...

How do I extract a floating number in the middle of an alphanumeric chain?

I am coding in Fortran 95. I must extract the two floating values from this line in an ascii file: circle(4097.0438,4111.337) Of course the READ statement is read(unit=11, fmt="(tr7,f9.4,tr1,f8.3)") x, y The problem is that I must do that for hundreds of ascii files, but there are variations in the...

Fortran memory allocation does not give an error, but the program is killed by OS at initialization

Given the minimal working example provided below, do you know why the memory allocation error does not occur at memory allocation step? As I checked, when I use valgrind to run the code, or add parameter source=0.0 to memory allocation statement, then I have, as expected, the memory allocation error....

Unable to modify variables from separate thread

So I'm making a C# app which has to continuously read and display the contents of a text file, while allowing the user to enter something into a text box and append it to the end of that very file. I'm doing this by running my read method on a...

How exactly do pointers in Fortran differ from C/C++ pointers?

It might be useful to have both C/C++ programmers and Fortran programmers compare and contrast pointers in these two languages. In trying to explain to C/C++ programmers how Fortran pointers differ, I usually say pointers to functions or subroutines do not exist. I then try to make the argument that...

Using Floor and Int in a computation

I am using a calculation to locate a base pixel. Seems to me that the two calculations for i and j are equivalent (i.e. i==j is always true) when I tried a few examples. Is this always true? i = (int ((x - xmin) / a)) + 1 j =...

Using BLAS ?gemm on a subset of an array in fortran

The various LDx arguments to BLAS ?gemm functions are there to make it possible to operate on slices of larger arrays. For example, this small C program does a matrix multiplication of the top left and top right (100,100) submatrices of a (200,200) matrix, and stores the result in the...

Checking all elements of array for a logical condition in fortran

I want to check all rows of an array for a logical condition. I used function ALL as described in GNU GCC guide Here is a sample code: program test3 implicit none real, allocatable, dimension (:,:) :: mat1 integer :: i,j,k,r logical :: lg r=3 allocate(mat1(r,r)) mat1=transpose( reshape( (/-1,-2,-3,-4,-5,-6,-7,-8,-9/),...

How do I load data from a txt file into variables in my C program?

I have a program that has a struct of channels: struct channel { char title[40]; float gain; float offset; }; int main (int argc, char **argv) { struct channel channels[8]; } And a text file called configurationSettings.txt that holds the information needed to fill up 8 channels: Title1 20 30...

Accessing open files globally in Fortran

Is there any means to accessing (reading, writing to) files that are opened in some other source code by just passing the unit number?

C++ and WinApi - usage of GetWindowText() to get parameters for C++ code

I have coded some C++ console program which converts one filetype to another. I need to turn the console application into a window one. I have never made window applications. I have chosen WinApi, because I don't have much time and don't want to change IDE (DEV C++ 5.10), compiler/linker...

When I write to two files in python, the second one is always empty

I'm working on a simple python script to write some data to two text files. My code looks like this: with open('file1.txt', 'w') as file1: for thing in stuff1: file1.write(thing + '\n') with open('file2.txt', 'w') as file2: for thing in stuff2: file2.write(thing + '\n') When I run the program, file1...

How can i store 2 numbers in a 1 byte char?

I have the question of the title, but If not, how could I get away with using only 4 bits to represent an integer? EDIT really my question is how. I am aware that there are 1 byte data structures in a language like c, but how could I use...

C++ basic fileIO locations

so I'm just starting to learn fileIO. I've been using a program called CodeRunner on my mac and I have a folder that contains: validsudoku.cpp, validsudoku, sudokugood0.txt The beginning of the code I wrote is: int main(int argc, char const *argv[]){ //string filetoopen; ifstream sudokutxtfile; string txtline; string sudokubox[9]; //bool...

Creating custom std::streambuf

I am defining a custom std::streambuf class for use in file I/O. In this class, I am overloading the functions open, close, is_open, xsgetn, xsputn, overflow, underflow, and uflow. I then insert this buffer into an std::ifstream as follows (the same scenario holds for std::ofstream): std::ifstream temp; Filebuffer *buffer =...

Cannot access LocalFolder files on Windows phone app (UnauthorizedAccessException)

I am trying to get an application to write (then read) a simple text file in Windows Phone 8. My app has three controls: a create file button, a display file button, and a textbox where the contents are supposed to display. I have the following events set up in...

Writing floats to a binary file in C++ | Equivalent of Java's DataOutputStream.writeFloat()

I'm porting some code from Java to C++ and need to write floats to a binary file. In Java I use DataOutputStream.writeFloat(). How do I do it in C++? I tried this method but it doesn't work: std::ofstream out;, std::ios::out | std::ios::binary); float f = 0.5; out.write(reinterpret_cast<const char*>(&f), sizeof(float));...

skip method in CipherInputStream

I am running into an issue where the code that works against a InputStream backed by a FileInputStream does not work if a CipherInputStream is used. Example is below: // skipCount is same as n in a FileInputStream FileInputStream fis; ... skipCount = fis.skip(n) Get a different behavior if a...

Getting Apache Camel to stop retrying if failed to move the file after route completion

The example route below picks up a file and performs a series of operations on them. Once completed, as noted in the camel:from field, the route is instructed to move the file to a .processed directory. Alternatively if failed, move it to the .error folder. The problem occurs when another...

Filling Multidimensional Arrays

I have created a derived type to access multi-dimensional arrays. With each array I associate a name in the array nm. My problem consists how to fill the array values once I have allocated the memory. An initial idea has been to use a multi-dimensional array as input. However I...

Cancel last line iteration on a file

I need to iterate on a file, stop iteration on a condition and then continue parse the file at the same line with another function (That may change so I can't just add content in the previous function). An example file (file.txt) : 1 2 3 4 5 6 7...

populate a 'JTable' with values from a '.txt' file

I'm new to java and I have a text file like this 0786160384|P. K.|Tharindu|912921549v|Colombo| 0711495765|P. K.|Gamini|657414589v|Colombo| 0114756199|H. P.|Weerasigha|657895478v|Kandy| I want to populate my 'jTable' with with the data from this text file. below is my code so far which doesn't work. When I execute the program nothing is displayed on...

Fortran Seg Fault when assigning Matrices

[UPDATE] the code and a few sentences were changed to reflect a realization explained in my second comment. The code should compile with the line below, however, I have an older gfortran and may not be seeing some errors that you might. gfortran BLU_implementation_copy.f90 -o BLU_implementation_copy.x I'm getting an incredibly...

Display an updated average of random numbers in a file

I have a program that displays one random number in file . #include <iostream> #include <fstream> #include <random> using namespace std; int main() { std::ofstream file("file.txt",std::ios_base::app); int var = rand() % 100 + 1; file<<var ; return 0; } Results after 4 trial : 1,2 2,20 3,40 1,88 I am...

Fortran compiler for mac to read program

I'm using the g77 compiler (on terminal I just type g77 filename.for ) on a Mac. It can't read my fortran program and I can't modify the program (very old program, not mine, and I really just need the output from it). Any suggestion for another compiler to read the...