Menu
  • HOME
  • TAGS

Append string to existing textfile in IronScheme

Tag: file,scheme,append,r6rs,ironscheme

We are trying to construct a log file using IronScheme, and we have written a code for it using racket. It works fine in racket, but IronScheme throws an error. This is what we have so far:

(define write-to-log
(lambda(whatToWrite)
(with-output-to-file "robot-log.txt"
(lambda () (printf (string-append whatToWrite "\r\n" ))) #:exists 'append)))

See how we use the "exists" optional parameter when using with-output-to-file. We are not sure how to make this optional parameter work with IronScheme. Are there any ways of getting this to work, or alternative methods?

Please note that we would like to append a string to an existing .txt file. If we don't use the optional argument, an error is thrown saying that the file already exists.

Best How To :

IronScheme supports R6RS :)

file-options are not available on with-output-to-file, so you need to use open-file-output-port.

Example (not correct):

(let ((p (open-file-output-port "robot-log.txt" (file-options no-create))))
  (fprintf p "~a\r\n" whatToWrite)
  (close-port p))

Update:

The above will not work. It seems you might have found a bug in IronScheme. It is not clear though from R6RS what file-options should behave like append, if any at all. I will investigate some more and provide feedback.

Update 2:

I have spoken to one of the editors of R6RS, and it does not appear to have a portable way to specify 'append mode'. We, of course have this available in .NET, so I will fix the issue by adding another file-options for appending. I will also think about adding some overloads for the 'simple io' procedures to deal with this as using the above code is rather tedious. Thanks for spotting the issue!

Update 3:

I have addressed the issue. From TFS rev 114008, append has been added to file-options. Also, with-output-to-file, call-with-output-file and open-output-file has an additional optional parameter to indicate 'append-mode'. You can get the latest build from http://build.ironscheme.net/.

Example:

(with-output-to-file "test.txt" (lambda () (displayln "world")) #t)

Read words/phrases from a file, make distinct, and write out to another file, in Java

java,file,sorting,distinct-values

You can leverage: NIO (Non-blocking I/O) API (available since Java 7) Streams API (available since Java 8) …to solve the problem elegantly: public static void main(String... args) { Path input = Paths.get("/Users/yourUser/yourInputFile.txt"); Path output = Paths.get("/Users/yourUser/yourOutputFile.txt"); try { List<String> words = getDistinctSortedWords(input); Files.write(output, words, UTF_8); } catch (IOException e) {...

Rust: Lifetime of String from file [duplicate]

file,io,rust

The string bound to "s" will be deallocated once the function ends ("s" goes out of scope), so you cannot return a reference to its contents outside the function. The best way is to return the string itself: fn read_shader_code(string_path: &str) -> String { let path = Path::new(string_path); let display...

C - Reading from a file

c,file,fgetc

/*Everything looks find in your code. in my machine it is working fine . I have only added a if condition to print the contents same as the file thats it .. */ #include<stdio.h> int main(void) { FILE *fp; int c; fp = fopen("rabi.txt","r"); if(fp == NULL) { perror("Error in...

How to have ImageIO.write create a folder path as needed

java,file,filepath,javax.imageio

you have to create the missing directories yourself If you don't want to use a 3rd party library you can use File.mkdirs() on the parent directory of the output file File outputFile = new File(nameAndPath); outputFile.getParentFile().mkdirs(); ImageIO.write(image, "png", outputFile); Warning that getParentFile() may return null if the output file is...

Buffered Reader read text until character

java,file,while-loop,bufferedreader,readline

It would be much easier to do with a Scanner, where you can just set the delimiter: Scanner scan = new Scanner(new File("/path/to/file.txt")); scan.useDelimiter(Pattern.compile(";")); while (scan.hasNext()) { String logicalLine = scan.next(); // rest of your logic } ...

Saying there are 0 arguments when I have 2? Trying to open a CSV file to write into

ruby,file,csv,dir

I believe the problem is with Dir.foreach, not CSV.open. You need to supply a directory to foreach as an argument. That's why you are getting the missing argument error. Try: Dir.foreach('/path/to_my/directory') do |current_file| I think the open that is referenced in the error message is when Dir is trying to...

ValueError: dictionary update sequence element #0 has length 1; 2 is required while reading from file

python,file,dictionary

dict() does not parse Python dictionary literal syntax; it won't take a string and interpret its contents. It can only take another dictionary or a sequence of key-value pairs, your line doesn't match those criteria. You'll need to use the ast.literal_eval() function instead here: from ast import literal_eval if line.startswith(self.kind):...

Java dir/files list

java,file,dir

Removed error from your version In your recursion you never ask for null values. Do it and it should run like this: public static List<File> listf(String directoryName) throws IOException { File directory = new File(directoryName); List<File> resultList = new ArrayList<>(); // get all the files from a directory File[] fList...

Reading a text file with Tabs

c#,asp.net,.net,file,readfile

There's no tab entity defined in ISO-8859-1 HTML, so I think you can replace tab characters with some &nbsp; characters: if (File.Exists(path)) { using (TextReader tr = new StreamReader(path)) { while (tr.Peek() != -1) { var htmlLine = tr.ReadLine().Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;") + "<br/>"; Response.Write(htmlLine); } } } ...

Is there a way to output file size on disk in batch?

file,batch-file,filesize

Interesting question. I'm not aware of the size on disk value being a property of any scriptable object. You could calculate it by getting filesize modulo bytes-per-cluster, subtracting that modulo from the file size, then adding the cluster size. (Edit: or use Aacini's more efficient calculation, which I'm still trying...

File not Uploading using Ajax in cakephp

php,jquery,ajax,file,cakephp

With this AJAX form submission approach, you will not be able to upload file using ajax. If you don't like using a third-party plugin like dropzone.js or Jquery file upload, you can use XMLHttpRequest. An example below: $('#newcatform').on('submit', function(ev){ ev.preventDefault(); var forms = document.querySelector('form#newcatform'); var request = new XMLHttpRequest(); var...

Open file under cursor declared as #include in the C/C++ code in Vim?

file,vim

You can use: gf to edit the file name under the cursor in the current window (requires 'nomodified' on the existing buffer in the current window). ^wf to edit the file name under the cursor in a new window. (Note: conveniently, ^w^f also works.) ^wgf to edit the file name...

How to know fast if another computer is accesible in AS3 (Adobe Air)

file,actionscript-3,air,lan

While I don't know of a method to make File.exists() perform faster (likely there is no way as it's more of an OS issue), you can at least mitigate the issue by using asynchronous operations instead - thus avoiding locking the UI. You can skip the exists operation, and just...

Python algorithm error when trying to find the next largest value

python,algorithm,file,output

I think your program is failing because you need to change: _getAvailableID(i) to return _getAvailableID(i) (At the moment the recursive function finds the correct answer which is discarded.) However, it would probably be better to simply put all the ids you have seen into a set to make the program...

Strings vs binary for storing variables inside the file format

c++,file,hdf5,dataformat

Speaking as someone who's had to do exactly what you're talking about a number of time, rr got it basically right, but I would change the emphasis a little. For file versioning, text is basically the winner. Since you're using an hdf5 library, I assume both serializing and parsing are...

File is not being downloaded when requested through Ajax using JQuery

javascript,jquery,ajax,file,csv

I would recommend you create the CSV at server side PHP program and set Content-Type as "application/vnd.ms-excel" (or) "text/csv" and set "Content-Disposition: attachment; [yourfilename] " Refer this Create a CSV File for a user in PHP Refer this Force Download CSV File Simply put hyperlink as <a class="areaSummaryExport" href="admin_ajax.php" value="1">...</a>...

Downloading file from Java servlet gives null

java,file,servlets,stream

This solution is a modified solution from BalusC File Servlet blog. The reason I use this solution is because it reset() the HttpServletResponse response before writing data. @WebServlet(urlPatterns = { "/Routing/*" }) @MultipartConfig(location = "/tmp", fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024...

Python - Select specific value from test file

python,file,text

You could split the text and have a list of lists, where each sub list is a row, then pluck whatever you need from the list using rows[row - 1][column - 1]. f = open('test.txt', 'r') lines = f.readlines() f.close() rows = [] for line in lines: rows.append(line.split(' ')) print...

How to test existence of 'file' that cannot be accessed?

c,file

Since the next thing we plan to do is create something at that location, and since we want to treat it as an error if something already exists there, then let's not bother checking. Just attempt the create and exit with an error if it fails. The create step uses...

Why is my linked list only printing last entry?

c,file,linked-list

The problem is the way you are treating the result of strtok: you are setting its value right into the node, instead of copying it. Make a copy of name when adding a node: void push(node ** head, int uid ,char* uname) { node * new_node; new_node = malloc(sizeof(node)); new_node->uid...

Storing multiple columns of data from a file in a variable

bash,file

Example code: #!/bin/bash declare -a textarr numarr while read -r text num;do textarr+=("$text") numarr+=("$num") done <file echo ${textarr[1]} ${numarr[1]} #will print Toy 85 data are stored into two array variables: textarr numarr. You can access each one of them using index ${textarr[$index]} or all of them at once with ${textarr[@]}...

Delphi - Use a string variable's name in assignfile()

file,delphi,variables,assign

Is it possible to use a variable in the AssignFile command? Yes. The second parameter of AssignFile has type string. The expression cFileDir + '\' + sFile has type string. FWIW, AssignFile is known as a function rather than a command. Getting on top of terminology like this will...

File security System in java? [on hold]

java,file,security,encryption

So to encrypt an aspect of the file you may want to gather it's bytes in an array*, That can either be done using the class Files from java or a stream to do it manually. For now lets say you got the byte array obtained using Files.readAllBytes(Path file); So...

How do I let the user name the output.txt file in my C program?

c,file

You can read the input from user and append .txt char fileName[30]; // ... scanf("%25s", fileName); // max 25 characters because .txt have 4 (25+4 = 29) strcat(fileName, ".txt"); // append .txt extension // ... FILE *f = fopen(fileName, "a"); ...

Read and Write the specific content

python,file

You first need to detect whether you are inside a "Bar" block. Then, while you are, print/accumulate those lines that start with * [x]. Here's one way to do it: def get_selected_block_entries(lines, block_name, block_prefix='#####', selected_entry_prefix='* [x]'): selected_lines = [] block_marker = '{} {}'.format(block_prefix, block_name) for line in lines: if line.startswith(block_prefix):...

Python - Deleting the first 2 lines of a string

python,string,file,parsing,lines

I don't know what your end character is, but what about something like postString = inputString.split("\n",2)[2]; The end character might need to be escaped, but that is what I would start with....

Python3 create files from dictionary

file,python-3.x,dictionary

Remove the if not len(key) != len(aDict) and the break. What you probably wanted to do is stopping the loop after iterating all the keys. However key is one of 'OG_1', 'OG_2', 'OG_XX', it's not a counter or something like that. Replace open("key", "w") with open(key + ".txt", "w")....

how to replace strings in a file by other strings in java

java,string,file,replace

First of all, the code you wrote here is not working, because when you open an outputStream to the exact file you try read from, it will empty the source file and the statement in.readLine() always returns null. So if this is your real code maybe this is the problem....

Assign hash to array

arrays,ruby,file,hash

You could do: size = Hash[arr.zip(arr_s)] To give you a better idea, in irb, I typed: a = (1..5).to_a => [1, 2, 3, 4, 5] b = ('a'..'e').to_a => ["a", "b", "c", "d", "e"] Then, typing size=Hash[a.zip(b)] Returns {1=>"a", 2=>"b", 3=>"c", 4=>"d", 5=>"e"} So you could do: puts size[1] which...

What is wrong with the function strtok()?

c,arrays,string,file,dynamic-memory-allocation

The problem with strtok is that the token it returns you becomes invalid as soon as you make the next call of strtok. You could either copy it into a separate string, or use it right away, and discard, but you must use it before calling strtok again. for (i...

Accessing call stack depth in Scheme

functional-programming,scheme,tail-recursion,callstack

Racket allows you to store values in the call stack. You can use this to keep track of the depth. Here is how I would do it: #lang racket ;;; This module holds the tools for keeping track of ;;; the current depth. (module depth racket (provide (rename-out [depth-app #%app])...

Am I allowed to use the .ttf format without paying licence fees?

file,fonts,true-type-fonts,legal,fees

You did not do your homework in looking up how fonts actually work before asking your question. Next time, please do. Now, while there exists a "ttf format", it has nothing to do with the font format itself, instead only specifying how to encode glyph outlines in a binary block...

Storing columns on disk and reading rows

c++,file,matrix,io

Mentioned solution with fseek is good. However, it can be very slow for large matrices (as disks don't like random access, especially very far away). To speed up things, you should use blocking. I'll show a basic concept, and can explain it further if you need. First, you split your...

Why the first byte of .png file is 0x89?

file,png,formats

Extract from http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature The first two bytes distinguish PNG files on systems that expect the first two bytes to identify the file type uniquely. The first byte is chosen as a non-ASCII value to reduce the probability that a text file may be misrecognized as a PNG file; also, it...

How to get rid of .ignore file in Git?

git,file,bitbucket,ignore

.gitignore is just like any other file under version control, so yes, you can delete it. However, keep in mind that it probably has entries in it that should be kept, so instead of deleting it, I would just modify it so that your jar files are no longer ignored.

Appending lines for existing file in python [duplicate]

python,file,python-2.7,io

The issue is in the code - curr_file = open('myfile',w) curr_file.write('hello world') curr_file.close() The second argument should be a string, which indicates the mode in which the file should be openned, you should use a which indicates append . curr_file = open('myfile','a') curr_file.write('hello world') curr_file.close() w mode indicates write ,...

How to upload file in PHP and store information in SQLi database?

php,file,mysqli,upload

I see you have called the bindParameters() method after calling execute(). It should be the other way round. i.e. $stmt->bind_param('ssis',$complete,$file_name,$fileSize,$myUrl); $stmt->execute(); ......

Python is returning false to “1”==“1”. Any ideas why?

python,string,file,integer,logic

By conversion to string, you hide the error. Always try repr(value) instead of str(value) for debugging purposes. You should also know, that it is better to compare integers instead of strings -- e.g. " 1" != "1". Edit: From your output, it is clear that you have an extra '\n'...

String Pattern Matching Algorithm Used in Different Applications [on hold]

arrays,string,algorithm,file,data-structures

For instance a single string matching is the z-algorithm. It's the fastest matcher.

Using MIT/GNU Scheme

scheme,edwin

MIT/GNU Scheme should start off as minimized. It is just a background console window that starts the editor. You need not pay attention to it (nor can you interact with it). Edwin: *scheme* is the Edwin text editor, which looks to me like some sort of Emacs derivative. It allows...

C++ reading and editing files

c++,file

This is the start of what you want. Because this is an assignment I have left you with some reading, and the remainder of the assignment. I have also translated much of the code to read in Portuguese. #include <iostream> #include <fstream> // seu códe // Faça isso para ler...

Realm.io Removing the realm file

ios,file,realm

That is the proper way of deleting it. You can check the Migration example in the RealmExample project that come with the SDK and see that that's exactly how they do it, so I assume the recommended way. let defaultPath = Realm.defaultPath NSFileManager.defaultManager().removeItemAtPath(defaultPath, error: nil) ...

Getting HTTP 302 when downloading file in Java using Apache Commons

java,file,url,apache-commons,fileutils

The code 302 refers to a relocation. The correct url will be transmitted in the location header. Your browser then fetches the file form there. See https://en.wikipedia.org/wiki/HTTP_302 Try https://repo1.maven.org/maven2/com/cedarsoftware/json-io/4.0.0/json-io-4.0.0.jar For FileUtils see How to use FileUtils IO correctly?...

How to make new line when using echo to write a file in C

c,linux,file,echo,system

There is one new line, which is to be expected. The echo command prints all its arguments on a single line separated by spaces, which is the output you see. You need to execute the result of: echo "$(ls %s)" to preserve the newlines in the ls output. See Capturing...

Group instances based on NA values in r

r,file,csv,instance,na

df[!is.na(df$Value), ] Size Value Location Num1 Num2 Rent 1 800 900 <NA> 2 2 y 3 1100 1300 uptown 3 3 n 4 1200 1100 <NA> 2 1 y And df[is.na(df$Value), ] Size Value Location Num1 Num2 Rent 2 850 NA midcity NA 3 y 5 1000 NA Lakeview NA...

Changing file name to the user's name PHP

php,file,upload

You need to change your $target_file variable to the name you want, since this is what gets passed into move_uploaded_file(). I don't see anywhere in your code where you actually set this variable to their username (right now it's still using the name they selected when they uploaded it). Without...

How can I create a PNG image file from a list of pixel values in Python?

python,image,list,file,python-imaging-library

Quick fix First, you need to have your pixel tuples in a single un-nested list: pixels_out = [] for row in pixels: for tup in row: pixels_out.append(tup) Next, make a new image object, using properties of the input image, and put the data into it: image_out = Image.new(image.mode,image.size) image_out.putdata(pixels_out) Finally,...

How to Write to a Certain Line in a File in VB

vb.net,file,file-access

I don't know if you can write to a specific line in a file, but if you need to you can write your lines to a List then write the list to a file 'Declare your list Dim lines As New List(Of String) For Each lineToWrite In YourLines If toInsert...

Check if file exists using Apache Commons VFS2

java,file,sftp,apache-commons-vfs

Use FileObject.exists() method. See https://commons.apache.org/proper/commons-vfs/apidocs/org/apache/commons/vfs2/FileObject.html#exists%28%29...

IllegalStateException: Iterator already obtained [duplicate]

java,file,loops,path

You have to call DirectoryStream<Path> files = Files.newDirectoryStream(dir); each time you iterate over the files. Pls check this question... java.lang.IllegalStateException: Iterator already obtained...