Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to read text from a file but it doesn't read all the characters, could someone please identify the problem

Contents of Text.txt
Test

main.cpp
C++
#include<iostream>
#include<cstdio>

using namespace std;

int main(){
    FILE* file;
    file = fopen("C:/Text.txt", "r");
    fseek(file, 0, SEEK_END);
    long Size = ftell(file);
    cout << Size << endl;
    fseek(file, 0, SEEK_SET);
    char* buf = new char[Size];
    fgets(buf, Size, file);
    cout << buf << endl;
}

Output:
4
Tes
Posted
Comments
Sicppy 17-Apr-14 17:53pm    
By the way, I realized I forgot to fclose(); it has been fixed.

1 solution

If foes not read all the characters because you are not trying to read them. You are seeking the end position. Remove that line, and the file will be opened in rewound position, at zero. Then read data in a single block or in a loop.

Also note that SEEK_END has no real standard portability. Better avoid using it:
http://www.cplusplus.com/reference/cstdio/fseek[^].

—SA
 
Share this answer
 
Comments
Sicppy 17-Apr-14 18:49pm    
Actually, the first fseek goes to the end byte, the ftell tells be where it is(giving me the size of the entire file) then I go back to the beginning, and use fgets to read the entirety of the file into a char*
Sergey Alexandrovich Kryukov 17-Apr-14 19:01pm    
Just remove it and don't use with SEEK_END. If you really want to read something at the end first, review your file structure. Put all "metadata" in the very beginning.
Anyway, are you going to accept the answer formally (green "Accept" button)? I told you all you need.
—SA
Sicppy 17-Apr-14 19:07pm    
No you haven't text files don't have meta, they're just an array of characters. Also, I'm not reading something at the end, I'm going to the end and then having it tell me where it is in the file so I know the size of the file, also, I've solved it myself, it actually gives me one less than the actual byte size for some reason.
Sergey Alexandrovich Kryukov 17-Apr-14 19:10pm    
What are you even talking about? I told you exactly what to do. Don't go to the end, you did not give me any valid reason for doing that.
—SA
Sicppy 17-Apr-14 19:20pm    
First of all, I go back to the beginning after going to the end. Second of all, I told you, the reason I go to the end, is to get the overall file size, if you go to the last byte in a file and read back where you are you will get the file size.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900