C编程读取文件并将其存储为字符串 [英] C Programming Read file and store it as a string

查看:66
本文介绍了C编程读取文件并将其存储为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了C代码,程序的输入值来自这里:

I wrote c code which input value for my program comes from here :

char *input[] = {"This input string value !!!", NULL};

但是如何从文件(例如input.txt)中读取此值?是否可以像字符串一样获取文件内容?

But how can I read this value from the file (e.g. input.txt)? Is it possible to get the file content like a string?

非常感谢!

推荐答案

如果要逐行读取文件,最简单的方法是使用getline.阅读手册页以获取详细说明和良好的代码示例.

If you want to read a file line-by-line, the easiest way to go is using getline. Read the man page for a detailed description and a good code example.

getline将为您完成所有低级的管道工作,包括分配缓冲区,复制数据和扫描换行符等.请记住,只有在getline使用动态分配的内存后,您才需要再次释放它.

getline will do all the low-lvel plumbing work of allocating buffers, copying data and scanning for newline characters, etc for you. Keep in mind that this is only possible since getline uses dynamically allocated memory that you'll need to free again.

这篇关于C编程读取文件并将其存储为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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