To read files I recommend to you to use an ArrayList: Scanner s = new Scanner(new File(//Here the path of your file)); ArrayList<String> list = new ArrayList<String>(); while (s.hasNext()) { list.add(s.nextLine()); } Now in your ArrayList you will have all the lines of your file. So, now, you can go...
It turns out to be a network problem. The connection speed to the drive where the excel file is located is slow.
java,excel,csv,io,html-parsing
It's a very good bet that writing CSV files will fix this since it appears the problem is Excel guessing how to put your text data into columns. Note that CSV is not a standard. CSV formats vary between different programs, e.g. how to do quoting and whether newlines can...
I am afraid it's impossible to run analize on a code-string. The pylint docs say: pylint [options] module_or_package Also, epylint.py: def py_run(command_options='', return_std=False, stdout=None, stderr=None, script='epylint'): """Run pylint from python ``command_options`` is a string containing ``pylint`` command line options; ``return_std`` (boolean) indicates return of created standard output and error (see...
c#,.net,io,filenotfoundexception
You're trying to move the entire directories with File.Move. You have to specify the file name as well: File.Move(file, Path.Combine(dp, Path.GetFileName(file))); ...
You cannot write outside of the /home/ directory by default. Also sudo is a command, you cannot execute a command from a BufferedWriter. So, launch your jar with sudo java -jar yourJar.jar or launch your IDE in root (for eclipse sudo eclipse). And try something like that: import java.io.BufferedReader; import...
You are attempting to write 36 bytes instead of 6, effectively accessing bytes beyond the end of the string. Definitely undefined behaviour. Only the first '\0' byte is expected. Use fwrite("Hello\n", 1, 6, cmd); Or more simply: fputs("Hello\n", cmd); ...
python,python-2.7,dictionary,io
This will ignore any lines without a '=', then from the remaining lines, remove any quotes and whitespace on the outside of each key and value, then put it into a dict: data = {} with open('in.txt', 'r') as fh: for line in fh: if '=' not in line: continue...
you're using the read method: note that this method can also throw an IOException. See the docs for the read method here, the declaration is: public final int read(byte[] b) throws IOException So you'll also need to catch IOException, or report that your method throws IOException. Note that you don't...
You are not reading the file at all in your extractTextFile() method. Files.write() is for writing the contents of the Arraylist to the file. You may want to use Files.readAllLines(path);...
c,io,printf,eof,format-specifiers
Using a wrong format specifier for any particular argument in printf() invokes undefined behaviour. EOF is of type int. You can only use %d for an int type variable. FWIW, if you want a floating point representation of an int, you have to cast the variable (but I personally recommend...
c++,file,io,typecasting-operator
In this statement why cast x to char* and not to bool* ... It suspect you are thinking that a bool, conceptually a single bit, is the most basic data type in C++. That is not the case. Individual bits are not addressable in C++. The C++ memory model...
Looks like you have all the Java and C++ code already in place. The missing puzzle piece seems to be the shell redirection. You should consult the manual of the shell you are using and look for redirection. In case you are using bash shell the redirection should look like...
I fixed the issue as follows: bytestream = io.BytesIO() midi.writeFile(bytestream) temp = io.BytesIO(bytestream.getvalue()) pygame.mixer.music.load(temp) As it seems, the writeFile() operation somehow makes the BytesIO object invalid to the pygame.mixer.music.load() method. By using the constructor of BytesIO again with the correctly created bytestream we magically get a valid bytestream we can...
You can just create a new child process with your_executable or alternatively with runInShell, create a new child process with the shell executable and pass -c your_executable to make the shell create a new child process with your_executable. For example if you want to execute bash builtins or if you...
java,io,velocity,resource-loading
Instead of using the full absolute path, load it from classpath, because it is already in classes folder. subjectTemplate = Velocity.getTemplate("velocityTemplates/terminalModerationStatusChanged.vm", "UTF-8"); ...
java,io,stream,java-8,java-stream
I think you can try: Stream<String> lines = new BufferedReader(new InputStreamReader(is, cs)).lines(); ...
python,multithreading,sockets,select,io
Though select() will work, you have to use threads if you want to do other things while the system is blocked on the select. Have a look at glib's GIO library. There you can connect callbacks to the actions you want to monitor or act on, for example the 'connect's...
java,parsing,input,io,bufferedreader
I think that either you: Normalize your key phrases and names (represent "word\nplus\nword" as "line n has word, line n+1 has plus, line n+2 has word") Process newlines as part of the matching characters (process byte by byte instead of line by line) From your current strategy, option 1 would...
Basically, you have two main C++-way choices: std::vector std::unique_ptr I'd prefer the second, since you don't need all the automatic resizing stuff in std::vector, and you don't need a container - you need just a buffer. std::unique_ptr has a specialization for dynamic arrays: std::unique_ptr<int[]> will call delete [] in it's...
javascript,audio,io,firefox-os,howler.js
Any file that is packaged in the app can be accessed using a relative url. Which means you don't have to get a blob or anything. It won't be possible to save assets (at runtime) in the app folder as far as I can tell. The only way to...
I did some quick profiling using only a single wchar_t per call, and there is indeed a noticable difference. First, the code: #include "stdio.h" #include "time.h" #include "wchar.h" wchar_t text[] = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$"; const int N = 64; const int M = 500000; int main() { int i, j; FILE *f1...
The problem is that you're opening the output file on every iteration. Instead, you should have both files open at the same time: using (var reader = File.OpenText(@"c:\test.txt")) { using (var writer = File.CreateText(@"c:\test2.txt")) { string line; while ((line = reader.ReadLine()) != null) { // Handle triggers or whatever writer.WriteLine(line);...
does read() add a '\0'? No, it doesn't. It just reads. From read()'s documentation: The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. Is there potential for error here, other than the...
As nobody answered my question, This link somehow help me through solving my problem. Log4j writes to files and the console serially. so while one thread is writing another thread that wants to write has to wait until the other one is finished. also, stdout can block if whatever is...
When called without arguments, io.read() reads a whole line. You could read the line and get the words using pattern matching: input = io.read() opr, txt = input:match("(%S+)%s+(%S+)") The above code assumes that there is just one word for opr and one word for txt. If there might be zero...
C doesn't interpret it. Your program reads 2 bytes and outputs same 2 bytes without caring about what characters (or anything else) they are. Your terminal encodes your input and reinterprets your output back as the same two byte character....
python,io,stdout,stringio,redirectstandardoutput
You're looking for sys.__stdout__: It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved...
As I said in the comment section, this can be achieved using MultiWriter package main import ( "io" "log" "os" "os/exec" ) func main() { // Logging capability f, err := os.OpenFile("log.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatalf("Error opening file: %v", err) } defer f.Close() mwriter := io.MultiWriter(f,...
python,file,python-3.x,io,text-files
unique = str(unique) + i + " " + str(newWords.count(i)) + "\n" The line above, is appending at the end of the existing set - "unique", if you use some other variable name instead, like "var", that should return correctly. def uniqueFrequency(newWords): '''Function returns a list of unique words with...
Let's look at the complete error message, which points to the error for us: <anon>:5:9: 5:14 error: mismatched types: expected `&core::result::Result<&str, ()>`, found `core::result::Result<_, _>` (expected &-ptr, found enum `core::result::Result`) [E0308] <anon>:5 Ok(s) => match s.parse() { ^~~~~ The compiler is expecting a &Result, but found a Result, and the...
From the docs http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.io.netcdf.netcdf_file.html NetCDF files, when opened read-only, return arrays that refer directly to memory-mapped data on disk: >>> >>> data = time[:] >>> data.base.base <mmap.mmap object at 0x7fe753763180> If the data is to be processed after the file is closed, it needs to be copied to main memory:...
No. You can only use streams on the channel socket if the channel is in blocking mode, in which case you wouldn't have a SelectionKey.
The bug is actually in your C++ program; it re-uses the in variable for both of its prints, which means if the second call to getline doesn't return anything (and it doesn't in your case, because the EOF of stdin is reached after the first getline call), the contents returned...
Use popen: FILE* file = popen( "grep mykeyword", "r" ); fwrite( str_to_grep, 1, strlen( str_to_grep ), file ); pclose( file ); The echo example by Matt might not work as expected if the string has quotes or similar character interpreted specially by the shell. I assume your example with grep...
python,string,io,stream,wrapper
You use open() to open the file, so it isn't a StringIO object, but a file-like object. To get the contents of the file after you write to it you can open the file with mode = 'w+', and instead of fd.getvalue(), do: fd.seek(0) var = fd.read() This will put...
I finally figured out how to bypass this error and successfully submit my app. Here is what you have to do if you already have armv7 included under build settings > valid architectures: Run the app on your phone with the usb cord pugged into the computer. Once the app...
The best way to know what it does is the standard 7.21.5.2 The fflush function Synopsis #include <stdio.h> int fflush(FILE *stream); Description If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for...
extracting from comments(duffymo's and mine) Pick a unique top-level package name. Example will be com.yourcompany or com.productname... etc In the exception handling routine, check if the package starts with your pattern. ...
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 ,...
python,io,race-condition,python-import,python-os
The way to do this is to take an exclusive lock each time you open it. The writer holds the lock while writing data, while the reader blocks until the writer releases the lock with the fdclose call. This will of course fail if the file has been partially written...
Here you go: use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let f = BufReader::new(File::open("/etc/passwd").unwrap()); let it = f.lines() .map(|line| line.unwrap()) .filter(|line| line.ends_with("/bin/bash")) .map(|line| line.split(":").next().unwrap().to_owned()); for p in it { println!("{}", p); } } This code allocates a separate string for each first splitted part though, but I don't think...
bool first = true; while((i = reader.Read()) > -1) { if (first) { first = false; // Do first character things } Note that the concept of first character is complex: what happens if the first glyph is è, that occupies two bytes in the file? The stream position will...
Here is a function f' which does what you describe. f' :: [(String,String)] -> IO [Bool] f' = mapM $ uncurry f Let me know if something is unclear! And, just to be clear, here is how you run it: main = do res <- f' [("a.txt", "b.txt"), ("c.txt", "d.txt")]...
The concrete file stream classes have their own rdbuf() method that takes 0 arguments and it hides the other rdbuf() method inherited from the virtual base std::basic_ios. Qualifying the name to lookup the base class method should work: std::ofstream ofs; ofs.basic_ios<char>::rdbuf(example.rdbuf()); ...
c#,linq,dictionary,io,statistics
I'd suggest to create custom class which can hold/store related data. Let it be Statisztika with the following fields/properties: Day, PersonId, Visitor and CountOfVisits. Statisztika class definition: public class Statisztika { private int iday = 0; private int ipersonid = 0; private int ivisitor =0; private int icount =0; //class...
Iterate through the directory, get each folder's properties, and get the TimeSpan difference from today to the folder's creation date. Try Dim dtCreated As DateTime Dim dtToday As DateTime = Today.Date Dim diObj As DirectoryInfo Dim ts As TimeSpan Dim lstDirsToDelete As New List(Of String) For Each sSubDir As String...
java,io,character-encoding,malformed
You can try to utilize the correct encoding by using the Files.lines(Path path, Charset charset) form of the lines method (javadocs). Here's a list of supported encodings (for the Oracle JVM anyhow). This post indicates that "Cp1252" is Windows ANSI....
Should be easier if you go easier ... var fs = require('fs'), readline = require('readline'); var rd = readline.createInterface({ input: fs.createReadStream('Domain.csv'), output: process.stdout, terminal: false }); rd.on('line', function(line) { console.log(line); }); ...
DataOutputStream.writeInt does not write an integer as text; it writes a "raw" or "binary" integer consisting of 4 bytes. If you try to interpret them as text (such as by viewing them in a text editor), you get garbage, because they're not text. For example, if your score is 100,...
You should seperate your reading logic from your update logic. for example: var replacements = dir.GetFiles() .Where(file => animals.Any(animal => file.Name.StartsWith(animal))) .Select(file => new { OldFullName = file.FullName, NewFullName = file.FullName.Replace(file.Name, "Animals-" + file.Name) }) .ToList(); foreach (var replacement in replacements) { File.Move(replacement.OldFullName, replacement.NewFullName); } Your replace logic has some...
perldoc -f open: In the two-argument (and one-argument) form, opening <- or - opens STDIN and opening >- opens STDOUT. I think this makes it clear that the special treatment of - is specific to the one- or two-argument forms. You could just assign \*STDIN to your $in, or open...
Yes it will "will it put one word in array[i] and the next word in array[i+1]". Note that nextToken() returns the next token from st string tokenizer. Be careful about the NoSuchElementException - if there are no more tokens in st tokenizer's string. Try something like this: while(st.hasMoreTokens() ) {...
To append to existing file use FileWriter with append = true argument in constructor: FileWriter fileWriter= new FileWriter(fileName,true); BufferedWriter bufferWriter = new BufferedWriter(fileWriter); bufferWriter.write(inputString); bufferWriter.close(); Read more about FileWriter here...
The issue is that after reading a float from the scanner, a newline "\n" is left in the scanner, this means that when the first scan.nextLine() runs, it gets that leftover newline, which results in your code hitting the else block, and breaking out of the loop. You can either...
From the documentation of System#console, it returns: The system console, if any, otherwise null. So your code is equivalent to: String firstName = null.readLine("What is your name? "); I would suggest you to use Scanner scanner = new Scanner(System.in); instead....
Your example is slow because it uses lazy IO with String-s. Both have their own overheads. In particular, String is a linked list of Char-s, therefore it has two words of space overhead for each character (one word for the constructor tag and one for the forward pointer), and each...
java,io,java.util.scanner,fileinputstream
Files contain bytes. FileInputStream reads these bytes. So if a file contains one byte whose value is 49, stream.read() will return 49. If the file contains two identical bytes 49, calling read() twice will return 49, then 49. Characters like 'a', '1' or 'Z' can be stored in files. To...
c,io,fortran,shared-libraries,abi
This is completely compiler dependent, there is no portable correspondence. See the manual of your compiler if they support some sort of interoperability as an extension.
You have newlines at the end of each filename: my @olap_f = `ls ~dir_to_file/*txt`; chomp @olap_f; # Remove newlines Better yet, use glob to avoid launching a new process (and having to trim newlines): my @olap_f = glob "~dir_to_file/*txt"; Also, use $! to find out why a file couldn't be...
You can use hSetFileSize to truncate a file to a given size.
Item 11 in your list is 0.09587, a real. You are using list directed input, which for a real is interpreted a numeric value using an F edit descriptor (Fortran 2008 Cl. 10.10.3 paragraph 4). An input list item corresponding to an F edit descriptor must be real or complex...
The last line of your read(s) will not return \n but an empty string, to indicate that the file was read completely. Why not use something like with open("testdata.txt") as infile: lines = infile.readlines() block = "" for line in lines: if line.strip() == "": break block += line you...
You essentially want to implement the Pipeline Pattern. If you're passing byte data, you've got a ready made implementation with the InputStream/OutputStream classes (where you'd extend FilterInputStream and FilterOutputStream). If you intend to pass objects, I recommend creating your own "object stream" classes (don't use ObjectInputStream/ObjectOutputStream, they're for serialization)....
You should only check errno if read returns -1 to indicate that it got an error. int n; if ((n = read(input, buffer_header, 4)) > 0) { image_width = bytesToInt(buffer_header); } else if (n == -1) { perror("read"); } else { printf("EOF\n"); } ...
Make the changes as below: while ((characterInt = fr.read()) != -1) { //characterInt = fr.read(); str += "" + (char) characterInt; } Read the char and compare it with -1 as EOF. You were appending the end of file char in string and then while loop condition was getting failed....
On Mac OS X, with FSF GCC 5.1.0, there is procedure Read (File : File_Type; Item : out Stream_Element_Array; Last : out Stream_Element_Offset; From : Positive_Count); where type Count is new Stream_Element_Offset range 0 .. Stream_Element_Offset’Last; subtype Positive_Count is Count range 1 .. Count’Last; --' -- Index into file, in...
python,file,python-3.x,io,count
The problem is quite simple: You split it into two function, but you completely ignore the result of the first function and instead calculate the number of words before the cleanup! Change your main function to this, then it should work. def main(): harper = readFile("Harper's Speech.txt") newWords = cleanUpWords(harper)...
Sometimes, there is good reason to be able to simply call a function to read a file and have the function return a pointer to an allocated array of strings holding the file's contents. This is especially true when you have no idea how long the file is. While you...
Primarily, terminals are just plain slow. For every update, they have to: Parse and interpret any control codes. Parse, interpret and render any escape codes. Interpret and account for any multibyte and composed characters. Update appropriate screen and scroll buffers. Render this with appropriate fonts. and possibly do all of...
Change the lines: if (inStream.bad()) { inStream.close(); outStream.open(filename); outStream << "This is a test file: \nWelcome to the Dark Side!"; outStream.close(); } inStream.open(filename, ios::in); if (inStream.good()) to if (inStream.bad()) { inStream.close(); outStream.open(filename); outStream << "This is a test file: \nWelcome to the Dark Side!"; outStream.close(); // Clear the state of...
use getline and stringstream while(getline(file,str)){ stringstream stream(str); double something; while(stream>>something){ //Push it into inner vector<double> } //push vector<double> into vector<vector<double> > here } You can work out the inner details yourself....
Turned out being a matter of redirecting stdin from parent to child process. See below: Perl's backticks/system giving "tcsetattr: Input/output error" Access STDIN of child process without capturing STDOUT or STDERR This is the solution: read_io, write_io = IO.pipe job1 = fork do write_io.close STDIN.reopen(read_io) puts `fab example` end Process.detach(job1)...
When you write to a file, the OS keeps track of the position at which you are in said file. You get an EOF error because you're at the end of the file (it was empty to begin with and everything you have written is before the current position). To...
StringBuffer stringBuffer = new StringBuffer(); try { InputStream is = mContext.getResources().getAssets().open("your-file-path"); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while ((line = br.readLine()) != null) { //play with each line here } }... Try this code to get data from the assets. OR if you don't want to...
According to the docs, savemat is defined as io.savemat(file_name, mdict, appendmat=True, format='5', long_field_names=False, do_compression=False, oned_as='row') So the 2nd argument is required, and may be provided with or without the mdict=... part. The reason why it expects this to be a dictionary is that it needs to know the name(s) under...
This snippet of code worked for me: Clip clip = null; ClassLoader cl = this.getClass().getClassLoader(); AudioInputStream ais; URL url = cl.getResource("com/example/project/assets/TestSound.wav"); System.out.println(url); try { ais = AudioSystem.getAudioInputStream(url); clip = AudioSystem.getClip(); clip.open(ais); } catch (Exception e) { e.printStackTrace(); System.exit(1); } The important thing is not adding the /src/ folder to the...
Use the csv module. import csv n = 3 m = 5 read = 0 with open("so.csv") as csvfile: reader = csv.reader(csvfile) for record in reader: read += 1 if read >= n and read <= m: print(record) ...
I have tested a null implementation of your code to see what is fwrite performance and I believe the bottleneck definitely isn't fwrite. #include <stdio.h> #include <string.h> char *icmDisassemble(int x, int y) { return "The rain in Spain falls mostly on the plain"; // return "D'oh"; // return "Quel ramo...
You have to check for the '+' and the trailing 'i': istream &operator>>(istream &input, Complex &complex) { char plus,letter; if (input >> complex.realPart >> plus) { if (plus!='+' ) input.setstate(ios::failbit); else if (input >> complex.imaginaryPart>>letter) { if (letter!='i') input.setstate(ios::failbit); } } return input; } Live demo here Note that you...
The basic problem is that this file has \r line endings. It also isn't valid UTF-8. Together, those are going to cause Scanner a lot of trouble. First, we can see exactly what's in the file using xxd 00000000: 2c2c 2c25 206f 6620 546f 7461 6c20 4578 ,,,% of Total...
When working with monad transformers, to convert from some monad m to a transformer t m, you have to use the lift function: lift :: (MonadTrans t, Monad m) => m a -> t m a This is actually the defining method of the MonadTrans typeclass, so the implementation is...
Combining ideas from the various answers with some extra bithacks, here is an optimized version: #include <errno.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define BUFFER_SIZE 16384 #define REPLACE_CHAR '@' int main(void) { /* define buffer as uint64_t to force alignment */ /* make it one slot longer to...
use Command + shift + 4, and you will get a crosshair. After you have outlines what is in the screenshot, press the space bar to capture. Hope this helps.
ProjectRoot is working directory for Eclipse. Move file above src directory i.e. to project root (Running from eclipse) openFile = new File("problem1.txt"); Provide path from src or bin to file location (Running from eclipse): openFile = new File("src/superbase/problem1.txt"); ...
io,fortran,intel-fortran,fortran2003
That looks like a compiler bug. The array grid is assumed shape, not assumed size. Assumed shape arrays are permitted in namelist as of F2003, assumed size arrays remain prohibited (at runtime the size of an assumed size array is not necessarily known, so operations that require knowledge of the...
For example, it can be done this way using async-await pattern: Task timeoutTask = Task.Delay(TimeSpan.FromSeconds(10)); // I use a completion source to set File.Copy thread from its own // thread, and use it later to abort it if needed TaskCompletionSource<Thread> copyThreadCompletionSource = new TaskCompletionSource<Thread>(); // This will await while any...
java,osx,io,external,runtime.exec
As I'd suspected, there was a problem with runtime itself! There's one more JavaFX app that acts as installer for this app (app with Runtime problems). For installation of this app I had used following code to copy contents of .app file: public static final void copyFile( File source, File...
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...
java,multithreading,windows-7,io
You simply had some typo in your FileMover run method: Path destination = origin.resolve(origin.getFileName().toString().replace(".in", ".out")); The destination will be like C:\temp\file_0.in\file_0.out this won't work, because it is a file and not a directory :-) Replace it something like that: String now = origin.toString().replace(".in", ".out"); Path destination = Paths.get(now); ...
The behavior I'm assuming would be to seek 5 MBs into the file and split the next 5 MBs into lines. You'd want something like: f.seek(5*1024*1024) lines = f.read(5*1024*1024).splitlines() Or manual counting (recommended method, much more efficient): f.seek(5*1024*1024) lines = [] while f.tell() < 10*1024*1024: line = f.readline(10*1024*1024-f.tell()) lines.append(line) However,...
This happens because the >> operator for the input stream only grabs part of a line, and does not always grab the newline character at the end of the line. When followed by a call to getline, the getline will grab the rest of the line previously parsed, not the...
On further reflection I realized it was because I had created the file earlier in the program and had not closed the file handle, and this was therefore perhaps a buffering issue. Closing the file earlier fixed the problem. It was suggested that I use "with" syntax for writing to...
Just because the declared type is OutputStream, that doesn't mean the implementation doesn't create an instance of a concrete subclass of OutputStream. You see this all the time with interfaces. For example: public List<String> getList() { return new ArrayList<String>(); } Basically you need to distinguish between the API exposed (which...
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...
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...
It ultimately comes to what you want to do with the data. If you want to create an instance of a class that stores the data for each entry in the file, the current parsing is probably fine. You can do it with key-value pairs like a hash map (or...