Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29246 Discussions

ifc 7.1: Can we use sprintf/printf/fwritef etc from C?

vsbabu
Beginner
1,073 Views
Hi,

Is it possible to call formatted write functions available in standard C. At least sprintf?

I am not sure how to handle this when we can have variable argument list. In C, you can call these functions with as many args as you need, but in Fortran, shouldn't sub-routines and functions have fixed number of arguments as set in the definition?

Thanks!
vsb
0 Kudos
2 Replies
Steven_L_Intel1
Employee
1,073 Views
All bets are off when calling outside Fortran. If you can figure out how to call sprintf, etc., from Fortran code, there's nothing stopping you from doing so. I will comment that C routines with "varargs" arguments require constructing the proper varargs data structure - it is not just passing a variable number of arguments.

It would be easier, I think, to call a C routine that does the sprintf for you.
0 Kudos
de-wei-yin
Beginner
1,073 Views
Instead of calling the C ?printf functions, how about calling Fortran's write statement in conjunction with a format specifier that utilizes the colon edit descriptor? You should be able to achieve the ?printf functionality this way unless you are trying to do something really tricky. Direct the output of the write statement to unit=* for printf behavior, to unit=file for fprintf, and to unit=character_string or unit=character_string_array for sprintf.

Note: (1) If unit=character_string or character_string_array, non-advancing I/O is not allowed. (2) If unit=character_string_array, the slash edit descriptor will direct I/O to the next element in the array. (3) You need to declare a sufficiently large character string (analogous to making recl large enough when writing to a file or to *). (4) There is no direct way of finding out the number of bytes read or written (the usual return values for ?printf). You can try len_trim() after the write, but it doesn't tell you about trailing blanks.

Similarly you can mimic the ?scanf function using the Fortran read statement, handling variable number of items using the colon edit descriptor.
0 Kudos
Reply