如何使用cstdio从文件中读取文本 [英] How to read text from a file with cstdio

查看:139
本文介绍了如何使用cstdio从文件中读取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文件中读取文本,但它没有读取所有字符,有人可以确定问题



Text.txt的内容

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


main.cpp

#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

推荐答案

如果敌人没有读取所有字符,因为您没有尝试阅读它们。你正在寻找最终的位置。删除该行,文件将在重绕位置打开,为零。然后在单个块或循环中读取数据。



另请注意 SEEK_END 没有真正的标准可移植性。最好避免使用它:

http://www.cplusplus.com/reference/cstdio/fseek [ ^ ]。



-SA
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


这篇关于如何使用cstdio从文件中读取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆