C语言将文本字符串输出,在C中,我应该如何阅读文本文件并打印所有字符串

这里有很多关于以块状态阅读它的好答案,我将向您展示一个小技巧,它将所有内容一次性读取到缓冲区并打印出来。

我不是说它更好。事实并非如此,而里卡多有时可能会很糟糕,但我觉得这对于简单的案例来说是一个很好的解决方案。

我在评论中撒了一些,因为有很多事情要发生。

#include

#include

char* ReadFile(char *filename)

{

char *buffer = NULL;

int string_size, read_size;

FILE *handler = fopen(filename, "r");

if (handler)

{

// Seek the last byte of the file

fseek(handler, 0, SEEK_END);

// Offset from the first to the last byte, or in other words, filesize

string_size = ftell(handler);

// go back to the start of the file

rewind(handler);

// Allocate a string that can hold it all

buffer = (char*) malloc(sizeof(char) * (string_size + 1) );

// Read it all in one operation

read_size = fread(buffer, sizeof(char), string_size, handler);

// fread doesn't set it so put a \0 in the last position

// and buffer is now officially a string

buffer[string_size] = '\0';

if (string_size != read_size)

{

// Something went wrong, throw away the memory and set

// the buffer to NULL

free(buffer);

buffer = NULL;

}

// Always remember to close the file.

fclose(handler);

}

return buffer;

}

int main()

{

char *string = ReadFile("yourfile.txt");

if (string)

{

puts(string);

free(string);

}

return 0;

}

让我知道它是否有用或者你可以从中学到一些东西:)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值