Skip to content

Commit d56f536

Browse files
committed
* _O_BINARY flag is needed to prevent _write and _read to interpret
CTRL+Z and end of file.
1 parent d972d77 commit d56f536

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

headers/fcntl.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,12 @@
2323
#define O_CREAT _O_CREAT
2424
#define O_WRONLY _O_WRONLY
2525
#else
26-
#include <fcntl.h> // open
26+
#include <fcntl.h> // open
27+
28+
// In linux _O_BINARY is not used. In Windows, this is needed to prevent
29+
// _write, _read to interpret CTRL+Z as EOL.
30+
// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/write?view=msvc-160
31+
#define _O_BINARY 0
2732
#endif
2833

2934
#endif

tea.c

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,15 +72,15 @@ bool encrypt_decrypt(int mode, char *key, int flags,
7272
}
7373

7474
// 2. Open the files
75-
if ((inf = open (in_file, O_RDONLY)) == -1) {
75+
if ((inf = open (in_file, O_RDONLY|_O_BINARY)) == -1) {
7676
perror("open - input");
7777
return false;
7878
}
7979

8080
// Feature output to stdout
8181
if ( outf == 0 ) {
8282
if ((outf = open (out_file,
83-
O_CREAT|O_WRONLY,
83+
O_CREAT|O_WRONLY|_O_BINARY,
8484
DEFAULT_FILE_CREATION_MODE)) == -1) {
8585
perror("open - output");
8686
close(inf);
@@ -95,15 +95,16 @@ bool encrypt_decrypt(int mode, char *key, int flags,
9595
memset(&d[len], 0, DATA_SIZE - len);
9696

9797
// Performs Encryption / Decryption operation
98-
printf("%.*s\n%.*s\n",DATA_SIZE,d,KEY_SIZE,key);
9998
if (mode == ENCRYPT)
10099
code ((uint32_t *) d, (uint32_t *) key);
101100
else
102101
decode ((uint32_t *) d, (uint32_t *) key);
103102

104103
// Write back
105-
if ((len = write (outf,d,DATA_SIZE)) < 0)
104+
if ((len = write (outf,d,DATA_SIZE)) < 0){
105+
perror("write");
106106
break;
107+
}
107108
}
108109

109110
// If write/read fails.

0 commit comments

Comments
 (0)