Reading and writing to files C++ -
this question exact duplicate of:
i've got problem regarding output/input files. here program:
#include <bits/stdc++.h> using namespace std; int main() { file * out; out=fopen("tmp.txt", "w"); for(int i=0; i<256; i++) { fprintf(out, "%c", char(i)); } fclose(out); file * in; in=fopen("tmp.txt", "r"); while(!feof(in)) { char a=fgetc(in); cout<<int(a)<<endl; } fclose(in); }
and here output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 -1
why stopping quickly? mean char(26)
eof
? how write file (of type) overcome problem?
i'm looking way freely write values (of range, can char
, int
or sth else) file , reading it.
works me *), few remarks:
- you should not use
#include <bits/stdc++.h>
, internal header intended compiler use, not included client apps. - as characters translated (e.g. eol) or interpreted in text (default) mode, should open files in binary mode.
- reading (signed) char , converting int result in negative values past 127.
- as
fgetc
returns int, not need conversion signed char , @ all.
see here the code corrections.
*) apparently mentioned in other comments it might not work on windows in text mode (see point 2.).
Comments
Post a Comment