You need to properly handle WM_KEYDOWN, not WM_COMMAND, because windows receives WM_KEYDOWN after key is pressed and WM_COMMAND after variuos of events. case WM_KEYDOWN: { if(wParam == VK_RETURN) { DWORD dlugosc = GetWindowTextLength( g_hText ); LPSTR Bufor =( LPSTR ) GlobalAlloc( GPTR, dlugosc + 1 ); GetWindowText( g_hText, Bufor, dlugosc...
When first time launching this file, be sure to select "change folder" instead of "adding file to path". When I selected "change folder" Matlab was able to write data in the 'output.txt' file. Also, as Dev-iL suggested I added append mode, final code looks like this function main clc; close...
Try something like this: (as taken from MS code examples) public class StackBasedIteration { static void Main(string[] args) { // Specify the starting folder on the command line, or in // Visual Studio in the Project > Properties > Debug pane. TraverseTree(args[0]); Console.WriteLine("Press any key"); Console.ReadKey(); } public static void...
I would do like this. from __future__ import with_statement mylist = [[1.0,'0:25.0','1:50.0'],[-1.0,'0:56.0','1:53.0']] # as example with open('output.txt', 'w') as f: for _list in mylist: for _string in _list: #f.seek(0) f.write(str(_string) + '\n') As a result, I get this in output.txt: 1.0 0:25.0 1:50.0 -1.0 0:56.0 1:53.0 ...
fstream Inoutput_file; void BackPatch(int GotoLineNo, string LineNo) { for (int i = 1; i <= GotoLineNo; i++) { char* str = new char[20]; Inoutput_file.getline(str, 20, '\n'); if (i == LineNo-1) { Inoutput_file.seekp(Inoutput_file.tellg()); Inoutput_file.getline(str, 20, '\n'); cout << str << endl; //prints the correct line Inoutput_file << "Goto " + str...
c#,if-statement,file-io,console
I think we're helping out with a school program here. There were several questions yesterday that dealt with almost the exact same issue and data. In the mean time, since you want to iterate your result set to look for the exact savings, I would recommend the following, instead of...
You can put the FileOutputStream into append mode for the second and subsequent writes, but you must also use an AppendingObjectOutputStream for the second and subsequent writes. You will find this class all over the Internet. It overrides writeStreamHeader() to do nothing. Otherwise you will get a StreamCorruptedException: invalid type...
javascript,design-patterns,file-io,webrtc,event-driven-design
There is a way to do that without timeout, although it uses flag to indicate that writer is available, it still should be better than timeout loop. I would create queue where data chunks will be stored when it arrives and use async fileWriter (one that does callback when it...
It appears that trying to do this with std::ifstream will not work, and I need to change it std::istream. Once I make this change, the overloaded functions are called and everything works properly.
What you did has nothing to do with binary files or audio. You simply copied the file while zeroing some of the bytes. (The reason you didn't zero all of the bytes is because you use i<strlen(buffer), which simply counts up to the first zero byte rather than reporting the...
Yes, that is possible (for both reading and writing). Here is a short example: module test_mod contains 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',...
The Linux/UNIX -tail command as described in the comments does not exist for windows, But yes, there are several ways to do this even without that command. Here is one that I have used, that should work cross-platform: First recognize you are describing a shared (file system) resource, that can...
c,file-io,struct,dynamic-memory-allocation
For every number of s_person there needs to be memory allocated for name and array s_person* construct(int number){ int each; s_person *person = (s_person*)malloc(sizeof(s_person) * number); if ( person) { for (each = 0; each < number; each++){ person[each].name = (char*)malloc(sizeof(char) * 50); person[each].array = (int*)malloc(sizeof(int) * 2); } }...
I got this to work. Just sharing the solution for the benefit of others. Technologies used: Jersey 2.x Jackson 2.4.x Jetty 9 Java 8 Dojo 1.10.x Below is the HTML <form> containing the dojox.form.Uploader, allowing the user to pick a file to upload. Note that uploadOnSelect is set to false...
Substitute printf("%d",&n); with scanf("%d",&n); printf Writes the C string pointed by format to the standard output (stdout) scanf Reads data from stdin In your code you are printing n, that is not initialized, that a random number is printed out after "Enter numbers to be stored in file" string....
You can use following snippet. With this code you need to know Maximum length of line. This code prints 5th character on each line on each word if its length is 5 or more.. Hope this work for you. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE 1000 int main()...
You read your file as a resource (getResourceAsStream("properties");). So it must be in the classpath. Perhaps in the jar directly or in a directory which you add to the classpath. A jar is a zip file so you can open it with 7zip for example add your properties file to...
c#,loops,if-statement,file-io,foreach
You could try something simple like this: //Making a list for file1 HashSet<string> listFile1 = new HashSet<string>(); string line; StreamReader sr = new StreamReader("file1"); while ((line = sr.ReadLine()) != null) { listFile1.Add(line); } sr.Close(); //Making a list for file2 HashSet<string> listFile2 = new HashSet<string>(); string line1; StreamReader sr1 = new...
java,multithreading,file-io,synchronization
java.lang.Thread's method join() allows you to wait for thread to exit. You can try using something like this: //wait for all threads to finish try { thread1.join(); thread2.join(); thread3.join(); } catch (InterruptedException e) { e.printStackTrace(); } ...
I guess you're not disposing the StreamWriter. See the example on MSDN. using( var writer = new StreamWriter(await file.OpenStreamForWriteAsync())) { writer.WriteLine("Hello World"); writer.WriteLine("Goodbye world"); } That's why your can't read the file, because it's already taken by SreamWriter....
Nowhere in your code have you specified the creation of the sub directories. Try something like: public class CreateDirectoryExample { public static void main(String[] args) { File worldDirectory = new File("C:\\Users\\xds\\Desktop\\world"); if (!file.exists()) { if (file.mkdir()) { System.out.println("World directory is created!"); } else { System.out.println("Failed to create World directory!"); }...
java,file,file-io,fileoutputstream
Make sure to always invoke the close() method of the output stream. This makes sure all buffered data are written to the stream. Also if you're writing characters, it's more convenient to use a FileWriter instead....
python,file-io,append,python-2.6
Okay, this will definitely fix your problem. fo = open("backup.txt", "r") filedata = fo.read() ix = filedata.index('ending') new_str = ' '.join([filedata[:ix], 'appending text', filedata[ix:]]) with open("backup.txt", "ab") as file: file.write(new_str) with open("backup.txt", "r") as file : print "In meddival : \n",file.read() As you can see, I am getting the index...
xml,vb.net,vba,file-io,filesize
If it's twice the size, then one is UTF-8 (the smaller one) and one is UTF-16 (the bigger one). In UTF-16, every ASCII character takes twice as much space as in UTF-8. (And Unicode means (in Windows) UTF-16)....
You need to check empty string before char operation. while ((line = bufferedReader.readLine()) != null) { if("".equals(line)){ continue; } char h = line.charAt(7); System.out.println(h); } ...
java,file,file-io,try-catch-finally
If you are using java6 or lower you could use a wrapper for you close(). public void closeStreams(Closeable c){ try{ c.close(); } catch(IOException e){ } finally{ // well noting here now.. } } And you can use : finally {//cerrando muestras if(muestras!=null){ muestras.closeStreams(); } if(salida!=null){ salida.closeStreams(); } } ...
No, you don't need to call fclose() inside if block. Once fopen() fails, it retruns NULL which need not be closed. To elaborate, if fopen() is success, it will return a FILE *. That needs to be closed. FWIW, the returned pointer in this case, be of whatever value, gurantees...
In cases where you absolutely don't know how to import your data, just use the Import Data GUI and generate a script. This is what you get for your case: %% Initialize variables. filename = 'C:\Users\Robert Seifert\Desktop\SO\data.txt'; delimiter = ','; %% Format string for each line of text: % column1:...
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...
So, as I see it, you have four questions you need answered, this goes against the site etiquette of asking A question, but will give it a shot How to list a series of files, presumably using some kind of filter How to read a file and process the data...
Updated Answer: Now that you've shown the full code, there are two major problems: You're trying to open the file before ensuring that the directories leading up to it exist, and You're using StandardOpenOption.APPEND, but that won't create a file; it will append to an existing file. ...along with a...
The a+ mode means append and read. Since you have initially opened the file in write-only mode (O_WRONLY | O_CREAT | O_EXCL), read access is not compatible with the mode of the initial descriptor. Therefore, the call to fdopen() rightfully fails with EINVAL....
haskell,file-io,lazy-evaluation
You're right, this is a pain. Avoid using the old standard file IO module, for this reason – except to simply read an entire file that won't change, as you did; this can be done just fine with readFile. readCsvContents :: Filepath -> IO String readCsvContents fileName = do contents...
c++,design-patterns,asynchronous,file-io,network-programming
You cannot do that (getting a non-OS specific file descriptor, or portably dealing with network sockets without any OS support). File descriptors & network sockets are an Operating System specific thing (or in the POSIX standard). The C standard library (from C99 or C11 standards) does not know them. fileno(3)...
You need to write logic in main(), that logic should : Create Company Objects Add Company Objects to ArrayList Read Contents from ArrayList Write Contents to File Use following main() code. public static void main(String[] args) { try { List<Company> companyList = new ArrayList<Company>(); Company c1 = new Company("Test Company","111",111,89077.0);...
The Problem: According to the CakePHP 2.0 book: Due to the limitations of HTML itself, it is not possible to put default values into input fields of type ‘file’. Each time the form is displayed, the value inside will be empty. While I'm sure there are ways you could hack...
I would say that Turing85 was correct. Your filename_date variable has slashes in it. So /Users/jchang/result_apache_log_parser_2015 has to exist as a directory. That is the cause of the NoSuchFileException, missing directory.
I'm guessing here, but your problem is likely that stuff1 and stuff2 are pointing to the same generator or iterator, and you can only iterate through once. After that, its contents are exhausted. Try this instead: import itertools stuff1, stuff2 = itertools.tee(the_source_generator_or_iterator_or_whatever) with open('file1.txt', 'w') as file1: for thing in...
As @chux said, the \x that VS is displaying to you is an inseparable part of the char representations that VS is presenting to you. It is trying to be helpful by providing a form that can be used directly in C source code as a char literal. For example,...
As much as it pains me to suggest it, this might be the one good use of MPI "Shared file pointers". These work in fortran, too, but I'm going to get the syntax wrong. Each process can read a row from the file with MPI_File_read_shared This independent I/O routine will...
python,python-2.7,text,file-io,editor
You need to close and re-open your file. print "This is a simple text editor" from sys import argv script, name = argv print "You have selected the file : %s" %name print "Opening the file...." t = open(name, 'r+') print "The contents of the file are" print t.read() t.close()...
I don't remember which old compiler was able to run functions without prototype. But I'll ask you to use: void transfer(Student *); And Also change: void transfer(Student myList[]); To void transfer(Student *myList) Additionally, the First sscanf in while should be: sscanf(buf, "%d,", &myList[ctr].studentNumber); You used 0 instead of ctr. Edit:...
java,hadoop,file-io,mapreduce,bigdata
You can Use Apache Pig to do Filtering and Validating Date format as well. Follow below steps : Copy your file into HDFS Load file using load command and pigStorage(). Select 20 column using ForEach statment (You can just give column name/number like $0,$3,$5..etc) Write UDF to validate date format...
You can ignore the rest of the line by using std::getline like that: settingsFile >> groupSize; std::getline(settingsFile, trash); settingsFile >> indTime; std::getline(settingsFile, trash); settingsFile >> newClientProb; std::getline(settingsFile, trash); settingsFile >> indTherapyCost; std::getline(settingsFile, trash); settingsFile >> groupTherapyCost; std::getline(settingsFile, trash); An alternative is to read the file line by line into a...
Even encryption won't stop editing of the file by something other than your application. Can I suggest that one option is to simply store the data in binary format? You then save the complication of implementing an encryption, but still prevent any accidental editing of the file. You could also...
python,file,python-3.x,file-io,operating-system
Alternatively you could memory map the file (using mmap). First find the last non-zero byte in the file, then check to see if any other bytes are changing after that. If you want to see if the file is still open by another process you could use lsof (you'd need...
c,arrays,parsing,file-io,struct
I won't be writing the code, but can try to help with the algotihm, in general. Open the file. Help : fopen() Check for successful opening. Hint: Return value. Read a line from the file. Check for the success. Help : fgets() and Return value. Based on data pattern ,...
Because you have ACCESS RANDOM in your SELECT, the default action for READ file-name (with no NEXT or KEY) is a keyed read. Change that to ACCESS SEQUENTIAL Change that to READ file-name NEXT anyway, which is an explicit sequential read. I always use an explicit NEXT or KEY on...
linux,performance,amazon-web-services,file-io
The following is a very coarse description of an architecture that can work for your problem, assuming that the maximum number of file descriptors is irrelevant when you have enough instances. First, take a look at this: https://aws.amazon.com/blogs/aws/amazon-elastic-file-system-shared-file-storage-for-amazon-ec2/ https://aws.amazon.com/efs/ EFS provides a shared storage that you can mount as a...
c#,multithreading,winforms,text,file-io
You've got multiple problems here, the use of the File is probably not thread-safe. your method does not repeat your are Sleep()ing on a Thread You can solve all of them by ditching the Thread and use a simple Timer. ...
A simple approach using Linq var lines = File.ReadLines(@"d:\temp\test.txt"); List<string> apollo = lines.Take(6485).ToList(); List<string> sabre = lines.Skip(6485).Take(6485).ToList(); Of course I take for granted that your file has effectively the number of lines that you have specified....
java,file-io,exception-handling,locking,apache-camel
This is something that the File component needs to handle, not your route. You can configure how the File component should handle locked files using the readLock option (along with other related options). The option has an extensive description on the File2 component documentation page...
c#,file,text,file-io,streamwriter
I have found the solution to my problem. I originally was passing in just the name of the file and not the whole path. Of course I missed one function call where I was still passing in the name of the file and not the path leading to the temp...
You are looking for lines where the entire line is equal to "Processed". From your comment it sounds like you only want lines that contain Processed, which can be done by using String.Contains: var aCount = a.Count(line => line.Contains("Processed")); ...
vals is a list. If you want to write a list of strings to a file, as opposed to an individual string, use writelines: ea=open("abc_format.txt",'w') ea.seek(0) ea.writelines(vals) ea.close() Note that this will not insert newlines for you (although in your specific case your strings already end in newlines, as pointed...
My attempt: #! /bin/bash if [ $# -gt 2 -o $# -lt 1 -o ! -f "$1" ]; then echo "Usage: ${0##*/} <filename> [<split size in M>]" >&2 exit 1 fi bsize=${2:-100} bucket=$( echo $bsize '* 1024 * 1024' | bc ) size=$( stat -c '%s' "$1" ) chunks=$( echo...
python,python-3.x,for-loop,file-io
In python3, the 'for line in file' construct is represented by an iterator internally. By definition, a value that was produced from an iterator cannot be 'put back' for later use (http://www.diveintopython3.net/iterators.html). To get the desired behaviour, you need a function that chains together two iterators, such as the chain...
There's nothing special about ENOSPC. It indicates that the write failed, and that reason why it failed has something do with the device not having enough free space to complete the operation. It doesn't leave the file descriptor in a bad or undefined state. The file descriptor remains in the...
So, yes, Windows passes the file name into the script as one of the sys.argvs. It is (so far as I can tell from printing the value) a file name without the path, that I used to open the file, so that tells me that Windows starts my program with...
java,algorithm,performance,file-io,data-structures
This depends on the way you implement parallelism in your data crunching part. At the moment you sequentially read everything - then crunch the data - then write it. So even if you broke it into 3 threads each one depends on the result of the previous. So unless you...
Let's take a look at the documentation for Result::unwrap: fn unwrap(self) -> T Unwraps a result, yielding the content of an Ok. Note how it takes self? That means that the option will be consumed. However, your iterator is passing the closure a &Result<T, _>. You can't take ownership of...
java,swing,file-io,jtable,stringtokenizer
you need to change your to something like this.you need to reset vector data = new Vector(); each time when you read new line otherwise it contain first row + second row + so on.and also you can call dtm.setRowCount(0); to avoid empty initial rows . and you need only...
It's your file mode. File.open("file", "wb") "wb" means "upon opening, truncate the file to zero length". I suggest "r+b", which means "reading and writing, no truncation". Read more about available modes here: http://ruby-doc.org/core-2.2.2/IO.html#method-c-new BTW, "b" in those modes means "binary" (as opposed to default "t" (text))...
What you want can be done using stdio and fseek(). As long as you know at what byte offset you want to go, you can overwrite and/or append anywhere in the file without reading the data before, or the data you're overwriting. What you can not easily do is insert...
the following is one way to handle the problem: for (int i=0; i<ROWS; i++) { for (int j=0; j<COLS; j++) { if (BOARD[i][j] == 0) { fprintf( fboard, " " ); } else if ( BOARD[i][j] == '@' ) { fprintf( fboard, "@" ); } else { fprintf( fboard, "%d",...
c#,visual-studio,file-io,delimiter
var oldLines = File.ReadAllLines(filePath): var newLines = oldLines.Select(FixLine).ToArray(); File.WriteAllLines(filePath, newLines); string FixLine(string oldLine) { string fixedLine = .... return fixedLine; } ...
Java's default behaviour is to write files (and any other data streamed to IO) in big endian. C++ writes files in native format. On a standard x86-derived PC native is little endian, so for 0.5 you get: 0x00 00 00 3f in C++ and 0x3f 00 00 00 in Java....
java,file-io,client-server,fileinputstream,fileoutputstream
The problem, I think, is that in after processing that command (GET) you are closing the server socket in that os.close() call. Realize that both os outputToClient and inputFromClient depend on the same server socket. Thus, when closing os you are impacting the other two streams. Then, after serving the...
Using OpenOptions::append is the clearest way to append to a file: use std::fs::OpenOptions; use std::io::prelude::*; fn main() { let mut file = OpenOptions::new() .write(true) .append(true) .open("my-file") .unwrap(); if let Err(e) = writeln!(file, "A new line!") { println!("{}", e); } } Of note is that you must use both write and...
arrays,string,matlab,file-io,cell-array
importdata does that for you: >> x = importdata('file.txt'); x = 'ABCCD' 'HGAQ' 'VBSER' >> whos x Name Size Bytes Class Attributes x 3x1 364 cell ...
You have ł in regex. You must changing coding for Unicode or remove it. If that will not work, check this "stuck" files if they contain some strange characters.
Even though it's kind of strange, what you are trying to do, and I'm sure there is a better way of doing it, here's how you can do it: float onTheFlyAverage() { static int nCount=0; float avg, newAvg; int newNumber = getRandomNum(); nCount++; //increment the total number count avg =...
A batch file solution isn't much fun, because batch can't really count or deal with arrays and indexes, it needs to work like: setup a counter, list the files, count through them, when the count matches the number you want, do something. @echo off setlocal enabledelayedexpansion set i=0 for %%f...
In case you ever have to break out more groups, you may want to consider storing your groups in a Dictionary<string, List<string>>, where the key is the group name and the value is the List containing only the group data. UPDATE If I'm understanding the scenario, say you have data...
These are the constructors on the java FileWriter 1.7 Constructor and Description FileWriter(File file) // Constructs a FileWriter object given a File object. FileWriter(File file, boolean append) // Constructs a FileWriter object given a File object. FileWriter(FileDescriptor fd) //Constructs a FileWriter object associated with a file descriptor. FileWriter(String fileName) //...
The program tries to find the file you open in the current working directory, not from the location where the executable file is. When you're executing a program from a terminal the current directory is the directory you're in. So if you do e.g. cd ~/ to go to your...
c#,asp.net-mvc-4,video,file-io
using system.IO; class program { static void main() { // Local Files File.Copy("path", "new Path"); } } ...
c#,asp.net-mvc,asp.net-mvc-4,file-io,webclient
To upload a file using HttpPostedFileBase you can use following snippet: public void UploadFile(HttpPostedFileBase file) { var folderName = "/Content/Upload/Images/"; var fileName = file.FileName; using (var fileStream = File.Create(BasePath + folderName + fileName)) { file.InputStream.CopyTo(fileStream); } } Folder where your files are uploaded is not a case as long as...
You are creating two instances of FileOutputStream and assigning both to out, but only closing one. Remove the second out = new FileOutputStream(new File(uploadedFileLocation));. Also, you should consider using a try-with-resources block private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) { try (OutputStream out = new FileOutputStream(new File(uploadedFileLocation))) { int read =...
javascript,c#,c#-4.0,file-io,filestream
As your FileReader is reading from your build destination not your project destination, it will not find the file (Look at that path it tires to read from, it is .\bin\Debug\script1.js, where your file will be at .\script1.js) The easiest fix is to change build action for your script file...
java,file-io,cryptography,inputstream
Found a solution that worked for me. Created a wrapper class that extended FilterInputStream and implemented the skip method using the same code found in InputStream.java Wrapper class public class SkipInputStream extends FilterInputStream { private static final int MAX_SKIP_BUFFER_SIZE = 2048; /** * Creates a <code>FilterInputStream</code> * by assigning the...
Calling to_i on a file handle returns the low-level identifier for it, a singular number, nothing more. If you want to operate on the bytes themselves: File.open(input_file, 'rb') do |f| File.open(output_file, 'wb') do |o| o.write( f.read.bytes.collect do |byte| byte ^ xor_value end.pack("C*") ) end end The key here is to...
java,file,file-io,bufferedreader
If you care about the memory wasted in the intermediate StringBuffer, you can try the following implementation: public static void skipLine(BufferedReader br) throws IOException { while(true) { int c = br.read(); if(c == -1 || c == '\n') return; if(c == '\r') { br.mark(1); c = br.read(); if(c != '\n')...
As you've discovered, fs.write with r+ mode allows you to overwrite bytes. This suffices for the case where the added and deleted pieces are exactly the same length. When the added text is shorter than the deleted text, I advise that you not fill in with \x00 bytes, as you...
I think a more direct translation of the original Python code is as follows: (with-temp-buffer (insert-file-contents "foo.txt") (while (search-forward-regexp "\\(.*\\)\n?" nil t) ; do something with this line in (match-string 1) )) I think with-temp-buffer/insert-file-contents is generally preferable to with-current-buffer/find-file-noselect, because the former guarantees that you're working with a fresh...
python,django,file-io,pandas,django-views
"Adding complete path and complete code in views.py, and I realized something, when I delete list function in views.py the graph worked just fine, I think there is a clash between list function and showimage function" Yes, indeed. Naming your view function list shadows the builtin type list in...
Use something like this: lines1 = File.readlines('file1.txt').map(&:to_i) lines2 = File.readlines('file2.txt').map(&:to_i) result = lines1.zip(lines2).map do |value1, value2| value1 - value2 } File.write('file1.txt', result.join(?\n)) This code load all files in memory, then calculate result and write it to first file. FYI: If you want to use your code just save result to...
This is not a bug or problem, rather, an expected behavior. Please read on. fgets() reads and stores the trailing newline (\n). you need to remove (strip) that before storing the input. That said, please note: Please don't allow boundless increment of i when you have defined a fixed size...
I would define the file as a field (in addition to the filename, and I suggest reading it from the user's home folder) file private File file = new File(System.getProperty("user.home"), filename); Then you can use the diamond operator <> when you define your List. You can use a try-with-resources to...
The problem is that in writefile() you read the stream until you reach the end of file. Once you do that the end of file flag in cin will be set and cin will longer read from input. You need to call clear() to remove the flag and continue reading.
It depends on where you want to write it, which isn't completely clear by your question. If you're always looking for the current user's documents, then you should look at the System.Environment.GetFolderPath method and the System.Environment.SpecialFolder.MyDocuments enumeration value in particular. When that executes, it will give you the path to...
I hard understand your question but maybe you want this. mensaxe will receive all items of array but 0 and 1 $mensaxe = array_slice($data, 2); You can trim all the array by array_map function: $mensaxe = array_map(trim, array_slice($data, 2)); UPDATE to output $mensaxe as a text, you can make string...
When a file is opened for read and write, an fseek() is used when switching between operations. fseek( fp, 0, SEEK_CUR); does not change the position of the file pointer in the file. #include<stdio.h> #include<stdlib.h> int main ( ) { int read = 0; int write = 48; int each...
There will be random garbage in the word variable because you never initialized it. Then read will only be able to get one byte from the file (nr probably returned 1, you should check that!) which saves one byte, but the word variable still has 3-7 bytes of uninitialized junk...
From the documentation on the open function: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -> file object ... buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text...