io,common-lisp,cffi , where is the text printed by C printf

where is the text printed by C printf


Tag: io,common-lisp,cffi

I happened encounter a trouble with calling C printf function from SBCL via cffi. The problem is when I call printf function, I can't find the output text, just the return value of printf function show on the REPL. But when I quit SBCL, the output text appears on the terminal magically.

  $ sbcl
  * (ql:quickload :cffi)
  * (cffi:foreign-funcall "printf" :string "hello" :int)
  ;;=> 5
  * (quit)

The last line, "hello$" means when quit from SBCL, the text "hello" appears on terminal and followed with the shell prompt "$". So where does printf print the text "hello" to?

I tried `finish-output', `force-output' on *standard-output* but that does not work.


The problem is that C's stdio library has its own buffering that has nothing to do with Lisp's. Flushing the output requires you to have a pointer to C's FILE *stdout variable. You can get this pointer like this:

 (cffi:defcvar ("stdout" stdout) :pointer)

Then, after using printf:

(cffi:foreign-funcall "fflush" :pointer stdout :int)


Backquote String Interpolation

Is it possible to use lisp's macro to do string interpolation? For instance, can I make a macro like this: (defmacro test (a) `",a") So that (test abc) returns "abc" as a string? I could probably cheat by quoting it and turning that quote into a string, but that doesn't...

If strings are vectors, why are they immutable?

if strings are vectors of characters, and a vector's elements can be accessed using elt, and elt is setf-able - then why are strings immutable?

Reading unformatted name/value pairs from a file, formatting it, and printing it out in Python 2 dictionary [closed]

Given a text file like so # Name_value_pair.txt name1 = value1 name2 = value2 name3 = "some value3" name4=value4 name5= name6 Is it possible to read that file, format it into a dictionary and print it out using python? I know how to open and read the files, but I...

how to save information from a file in java

I am supoose to read a file lets say it has 3 lines: 2 Berlin 0 2 2 10000 300 Nilreb 0 2 2 10000 300 the first integer number shows how many names(lines) i have. the 2nd and 3rd lines show information about two post offices. them i am...

Insertion into a list doesn't reflect outside function whereas deletion does?

I am new to Lisp. Deletion of an item in a list by a function gets reflected outside the function but insertion doesn't. How can I do the same for insertion? For example (defun test (a b) (delete 1 a) (delete 5 b) (append '(5) b) (member '5 b)) (setq...

Invalid specialized parameter in method lambda list

I am trying to write a simple coin flip program in Common Lisp. This is the code I have (defun yn (let ht (random 1) (if (eq ht 1) (princ heads) (princ tails)) ) ) It seems simple enough, but I keep getting the error: "Invalid specialized parameter in method...

Rust: Lifetime of String from file [duplicate]

This question already has an answer here: Return local String as slice 1 answer I'm trying to read in some external GLSL code into Rust. The reading works properly, but I run into a lifetime issue in the final expression (in the Ok(_) branch) error: s does not live...

How fast can we make a specific tr?

I had to replace all the null bytes in a file with another character (I arbitrarily chose @), and was pretty surprised that tr '\00' '@' was about 1/4 the speed of gzip: $ pv < lawl | gzip > /dev/null ^C13MiB 0:00:04 [28.5MiB/s] [====> ] 17% ETA 0:00:18 $...

Why does grep give “Binary file (standard input) matches”?

#include <stdio.h> int main() { FILE* cmd = popen("grep Hello", "w"); fwrite("Hello\n", 6, 6, cmd); fwrite("Hillo\n", 6, 6, cmd); fwrite("Hello\n", 6, 6, cmd); pclose(cmd); } The program above outputs: Binary file (standard input) matches Why does grep give the message, and how to fix it?...

In ubuntu unable to write file in specified directory using java

While trying to write file in specified directory i am getting exception. Java code :- public void jsonToYaml(JSONObject json, String studioName) throws JSONException, org.codehaus.jettison.json.JSONException, IOException { Yaml.dump(Yaml.dump(JsonToMap.jsonToMap(json)), new File("config.yml")); BufferedReader br = new BufferedReader(new FileReader("config.yml")); String line; studioName = studioName.toLowerCase(); File writeFile = new File("sudo /var/iprotecs/idns2.0","" + studioName + ".yaml");...

Mapping with IO actions in Haskell

I have a function that takes two filenames, and reads the contents of those two files into Strings, and then returns if they match or not. Here's the function: f :: String -> String -> IO Bool f fileName1 fileName2 = do str1 <- readFile fileName1 str2 <- readFile fileName2...

C - does read() add a '\0'?

Does it have to? I've always been fuzzy on this sort of stuff, but if I have something like: char buf[256]; read(fd, buf, 256); write(fd2, buf, 256); Is there potential for error here, other than the cases where those functions return -1? If it were to only read 40 characters,...

how to write the output of iostream to buffer, python3

I have a program that reads data from cli sys.argv[] and then writes it to a file. I would like to also display the output to the buffer. The manual says to use getvalue(), all I get are errors. Python3 manual import io import sys label = sys.argv[1] domain =...

Sequential file IO from different threads fail with FileSystemException

I am trying to see how fast i can do something like: write a small file rename it delete it This basically looks like: import; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class QuickIO { public static void main(String[] args) throws IOException { Path fileToWriteTo = Paths.get("C:\\Temp\\somefile.txt"); Path fileToMoveTo...

IO reading (java)

if i have a loop like so: while(st.hasMoreTokens() ) { array[i] = st.nextToken(); array[(i+1)] = st.nextToken(); i++; } will array[i] and array[i+1] end up having the same word or will it put one word in array[i] and the next word in array[i+1]? i'm trying to read in 2 words at...

how to read in files made of double values line by line using c++

I'm trying to do something very simple, but just can't get it right... Working with C++, I want to read in "myfile.tsv" which looks like this: 2.3 3.3 3.4 3.5 5.6 \n 1.2 1.3 1.2 \n 3.4 3.5 3.5 \n 4.4 4.6 1.3 1.5 \n ... many lines of double...

Issue reading and saving lines from .txt file in Java

Objective & Issue Objective of the task I am trying to accomplish is to locate and read a text file from a provided path then copy each line of the text file into a ArrayList<String>. This "ApplicationFileReader" object is created in some control class by calling the constructor which takes...

sbcl run-program hang when there is large amount of output from program

Recently I find a run-program hang issue of sbcl 1.2.7 (32bits, linux). The code as following (progn (with-open-file (s "test.out" :direction :output :if-exists :supersede) (loop repeat 900 do (write-line (make-string 76 :initial-element #\x) s))) (run-program "/bin/bash" (list "-c" "cat test.out") :output :stream)) That is when the "cat test.out" produce many...

Why is it slower to print directly to console/terminal than redirecting?

Why does it take significantly more time to print multiple lines to the terminal rather than redirecting it to a file which seems to be almost instant ?

Structuring large Lisp applications

I am currently trying to wrap my head around packages, systems & co. I now have read Packages, systems, modules, libraries - WTF? a few times, and I think I'm still having difficulties to get it right. If I simply want to split a Lisp source file into two files,...

Mixing Java NIO with IO input streams read operation

I need to use NIO to allow the server side to support timeout on write operations, but handling reading operations on the socket channels complicates my program. I was wondering if it's possible to write to the sockets using NIO but to read using regular IO, something like ((SocketChannel)

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...

Read input into string in Lisp reader macro

I am trying to make a reader macro that would convert @this into "this". This is what I currently have: (defun string-reader (stream char) (declare (ignore char)) (format nil "\"~a\"" (read-line stream t nil t)) ) (set-macro-character #\@ #'string-reader ) The problem is that this requires that I put a...

How to read a middle size-specified chunk of a file in Python

If I have a text file, what is a clean way to start from a line at near the 5th MB into the file and read the subsequent 5 MB worth of lines into a list? Ideally into a list of lines. I know starts at the 5th MB,...

EVAL/APPLY: too many arguments given to F

Hello why do i get *** - EVAL/APPLY: too many arguments given to F on function call with nested lists parameter. I cannot figure it out, since I passed a simple nested list. (defun f (L) (cond ((NULL l) nil) ((listp (car L)) (append (F(car L))) (F(cdr L) (car (F...

Updating the window in response to CLIM frame commands

While trying to figure out CLIM, I ran into this example program. It's a simple maze game. The author claims to have tested it in LispWorks (and even has #+Genera in there, implying that this program would work on a real Lisp Machine), but I'm trying to get it working...

how to reattach sys.stdout to console window in python?

My python 3 doodling went like this: import io, sys sys.stdout = io.StringIO() # no more responses to python terminal funnily enough My question is how to reattach so when I pass in 1+1 for example it'll return with 2 to the console? This is in the python interpreter on...

monitor log4j behaviour under load

I want to test my J2EE application under high load of sessions accessing different pages. This web application uses Log4J to log bunch of errors,warnings and infos. I want to test what is the side effect of this load on writing log files, especially concurrent I/O writing actions. I found...

Appending lines for existing file in python [duplicate]

This question already has an answer here: How do you append to a file in Python? 6 answers I want to add lines to an existing file in python. I wrote the following two files while True: curr_file = open('myfile',r) lines = curr_file.readlines() for line in lines: print...

C++ not reading anything from files

I seem to be having a problem reading files. I am using Visual Studio Community 2013 and it will do everything but reading of files. I have checked to make sure the file being read and written is in the same directory. The following code is where I believe the...

How to grep a string in a program?

#include <stdlib.h> int foo(char *str_buf_to_grep) { // How to write the following line correctly? return system("??? str_buf_to_grep ??? | grep mykeyword"); } Description: The str_buf_to_grep is given in any way, which might be the content of a text file, and might be very long and complex, even contains special characters,...

where is the text printed by C printf

I happened encounter a trouble with calling C printf function from SBCL via cffi. The problem is when I call printf function, I can't find the output text, just the return value of printf function show on the REPL. But when I quit SBCL, the output text appears on the...

OutputStream class is used for writing into files. How is it possible?

The below code is quoted from : Although the OutputStream is an abstract method, at the below code, OutputStream object is used for writing into the file. Files.newOutputStream(filepath)) returns OutputStream. Then, the type of out is OutputStream, and out references OutputStream. How can this be possible while OutputStream is...

How to improve the performance of Haskell IO?

It seems that Haskell's IO is relatively slow. For example, comparing Haskell with Python import sys sys.stdout.write(s) , -- io.hs main = do s <- getContents putStr s Their performance ( writes 512k data into stdout): The Python version: $ time python | python > /dev/null...

input errors : split part of one entery

i am doing some practice on standard I/O i have a complex class . my class has overloaded insertion and extraction operators ,the input should of the form : x + yi(e.g 10 + 9i) i have to determine if input is valid or not . there is the problem...

What is a common-lisp analogue of python's argparse?

What is a common-lisp analogue of python's argparse library for parsing command-line arguments?

EMACS-Live + Slime error at startup

Ok, I must be missing something obvious. I'm getting stuck since yesterday to launch Emacs-live + slime. I'm using EMACS 24.3.1, installed Emacs-live and it worked well (if I start emacs-live without Slime it works), downloaded Slime-Pack from git and added this line to .emacs-live.el (live-append-packs '(~/.live-packs/slime-pack/)) I'm on a...

How can I redirect, in Go, the stdout and stderr of a command to both the console and a log file while outputting in real time?

The following bit of code does exactly what I want, except it only prints to the console. cmd := exec.Command("php", "randomcommand.php") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } randomcommand.php: // randomcommand.php simply alternates output between stdout and stderr 20 times $stdout...

Pylint on StringIO or buffered text

I need to analyze some code generated "magically" in a function. The example I'm using is very simple. Here is what I intend to do: from pylint import epylint from StringIO import StringIO source = StringIO() source.write('def test():\n') source.write(' b = 5\n') source.write(' return\n') epylint.py_run(source) The result I get:...

Output EOF using %f

#include<stdio.h> int main() { printf("%d",EOF); } generates -1 which is totally fine, but #include<stdio.h> int main() { printf("%f",EOF); } produces 0.000 . How can someone explain this when the expected output is -1.000?...

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...

Fortran runtime error “bad integer for item 11 in list input”

I receive the runtime error "bad integer for item 11 in list input" referencing the following line of code. read(2,*)a,b,c,d,e,f,g,h,theta1,phi1,k,l,m,n,o, $ p,theta2,phi2,s,theta3,phi3, $ r1,x1,y1,r2,x2,y2,r3,x3,y3,z1,z2,z3 The line its reading from is 1 255.11211 0.2876 165.11404 90 4 8 0.19173 90 165.11404 0.09587 90 345.11404 4 4 0.0764 89.99915 -64.51149 0.11131 90.0015...

In the dart:io library, why would one want to set runInShell: true when calling

What functionality does this offer? Furthermore, how does the process get called when runInShell is set to false? What's the difference?

Storing columns on disk and reading rows

So I have a C++ code that finds the inverse of a square matrix. The inverse is full and it would be bad to keep it all in memory because I am working with hundreds of thousands of columns. My code generates the columns one by one. After finding the...

the logic behind the diffrerence between fileInputStream and Scanner classes

I'm trying to understand the difference between Scanner.nextByte() and I read similar topics, but I didn't find the answer of my question. A similar question is asked in the topic : Scanner vs FileInputStream Let me say what I understand : Say that a .txt file includes 1 Then,...

javscript readstream line by line

I'm trying to read in a CSV file line by line and add each line to an array, my code so far is: var csvFile = 'Domain.csv'; var fs = require('fs'); var readableStream = fs.createReadStream(csvFile); var data = ''; readableStream.on('data', function(chunk) { var temp = ''; temp = chunk; global.qArray.push(temp);...

how to effectively write text file in C and the size of file would be 5GB

FILE *fp; fp = fopen(pch, "wb"); while(1) fwrite(p, sizeof(char), strlen(p) / sizeof(char), fp); I used these codes to write to txt file, however when the output file is very big (It's size may grow up to 5GB) it will be very slow, I need to wait a long time. Can...

Local dynamic binding in common lisp

Honnestly, I'm not sure I fully understand what it means for a binding to be "dynamic" versus "lexical". But I understand that when I use defvar or defparameterto define a binding, 1. it declares a global variable 2. the binding is declared "special", so that it can be shadowed by...

Custom streambuffer in std::ofstream

I know that in std::ostream, I can use a custom streambuf through either stating so in the constructor: std::ofstream temp;"file.txt", std::ios_base::in); std::ostream example(temp.rdbuf()); as well as by setting it afterwards (same first two lines as before, but change the last line to: std::ostream example; example.rdbuf(temp.rdbuf()); My question is: How...