从C语言的文本文件中读取信息
我是 C 语言新手;请尽力帮助我。 我得到的参数是指向文件的 main()
指针, 因此,在 for 循环中,我 fopen()
它们并希望将它们发送到一个函数,该函数将 读取其中的文本信息并将其放入 char 变量中。
这是一个示例文件:
#station name Station Name : A1 #octan of fuel 6.54 full service price 6.40 self service Octan95,6.54,6.40 Octan98,8.30,8.15 #carNum,Octan,numOfLiters,Kind of service 22-334-55,95,31.3,FullService 22-334-55,95,31.3,SelfService 11-444-77,95,12,FullService 11-444-77,95,44.1,FullService 11-444-77,95,11.22,SelfService
文本具有用逗号分隔的字段,我需要将这些逗号之间的信息添加到变量中。 读取这些文本文件的最佳方式或功能是什么? 另外,我是否应该在每一行之后期待 '\n'
,还是将其作为一个大的 char[]
进行流式传输,而无需换行符?
I'm new to C; please try to help me as much as you can.
I'm getting as arguments to main()
pointers to files,
so in a for loop I fopen()
them and want to send them to a function that will
read the text info inside them and put it in char variables.
Here is an example file:
#station name Station Name : A1 #octan of fuel 6.54 full service price 6.40 self service Octan95,6.54,6.40 Octan98,8.30,8.15 #carNum,Octan,numOfLiters,Kind of service 22-334-55,95,31.3,FullService 22-334-55,95,31.3,SelfService 11-444-77,95,12,FullService 11-444-77,95,44.1,FullService 11-444-77,95,11.22,SelfService
The text has fields separated with commas, and I need the information between those commas to be added to vars.
What will be the best way or function to read these text files?
Also should I expect '\n'
after each line or will it stream as one big char[]
without the new line character?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
逐行读取文件
使用 strtok 函数获取逗号之间的所有内容
read file line by line
use strtok function to get everything in between commas
逐行读取文件并使用带有返回值的 sscanf 来获取逗号之间的所有内容
read file line by line and use sscanf with return-value to get everything in between commas
稍后大约 200 行代码...并使用数据文件的稍微修改版本(请注意,原始文件中的第二个标题行缺少所有逗号):
该代码在大多数意义上都不是最佳的 - 它分配了太多小块内存。我也懒了,没有写释放内存的代码。不过,我认为将其作为您的代码提交并不是一个好主意。
Some 200 lines of code later...and using a slightly modified version of your data file (note that the second header line in the original is missing all the commas):
The code is not optimal in most senses - it allocates far too many small bits of memory. I also got lazy and didn't write the code to free the memory. I don't think it would be a good idea to hand this in as your code, though.