Reading a text file......

Hi.
What is wrong with me reading the text file?
1
2
3
4
5
6
7
8
9
10
11
12
int main(){
...........
    int fh = _open("g://PA2//10.txt" , fh);
    fh=_read(fh,a,70000);
...............
    for(int k=0;k<20;++k)
       cout << a[k] <<' ';

    cout<< endl;  
.................
return 0;
}
Last edited on
You need to specify in what mode you want to open the file.
You also need to check if the file could be opened.
1
2
3
int fh = _open("g://PA2//10.txt" , _O_RDONLY);
if (fh <> -1)
  // read your file here. 


See here for documentation and example:
https://msdn.microsoft.com/en-us/library/z0kc8e3z%28v=vs.100%29.aspx
Thanks.But the problem is this:

I need to print my file this way:
1
2
3
4
    for(int k=-4;k<100;++k)
       cout << a[k] <<' ';

    cout<< endl;  


A problem I have never faced in my whole life!



Last edited on
I need to print my file this way:
1
2
for(int k=-4;k<100;++k)
  cout << a[k] <<' ';


Why?

I guess a is a kind of array and the first element is a[0].
If you try sth. like cout << a[-4] it will most likely crash.
I could not figure out myself

That worked for an ad-hoc content and not for another content.
Last edited on
What is the problem ?
After reading, I'd have strange characters in my file.
Then when I convert them to numbers, I get unexpected results.
Can you post part of the file?
How was a declared?

Are you sure you've actually read the number of characters you're trying to print?

Wouldn't it be better to use the value returned from your _read() call to control your loop?

The file:
3
9
8
4
6
10
2
5
7
1
------------------------------------------------
Def. of a:
char a[700000];
Why are you trying to read a series of numbers as a series characters?

And why are you trying to use the low level function _open() instead of the higher level functions? If you're writing a C function fopen() or in C++ using the file streams.
OK, I was making a stupid mistake in making fh get the value of _read(fh, ...)
Interesting.................I was taught that the RHS of the assignment gets evaluated first.
Topic archived. No new replies allowed.