阅读在C文件 [英] Reading a file in C

查看:119
本文介绍了阅读在C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的朋友和我工作的一个项目,我们需要从在C文件中读取输入。

My friend and I are working on a project, and we need to read input from a file in C.

文件看起来是这样的:

15 25 200
3 10
17.99 22.99 109.99
100 2 4
5.99 99.99 20.00 49.99
10 10 10 10 10 10 10 10 10 10
3.99 5.99 7.99 8.00 5.00 5.00 5.00 6.00 7.00 9.99
5

我需要读取线的文件中的行,并设定为等于一个不同的变量的每个值。例如,在第一行中的第一个值必须设置为变量preSalePrices,第二值doorPrices和第三preSales。我需要帮助搞清楚如何指定每行的值的数量。例如,我怎么告诉程序在第一行拿到三个值,但只有两个在第二行?然后在第五行四个值,并依此类推。

I need to read the file line by line, and set each value equal to a different variable. For example, the first value on the first line must be set to the variable preSalePrices, the second value doorPrices, and the third preSales. I need help figuring out how to specify the number of values on each line. For example, how do I tell the program to get three values on the first line, but only two on the second line? Then four values on the fifth line, and so on.

下面是我的code,但它只是崩溃了:

Here is my code, but it just crashes:

int main() {
    float preSalePrices, doorPrices;
    int preSales;
    FILE *fp;
    fp = ("C://Users//Jake//Desktop//Charity Ball//auction01.txt", "r");

    while(fscanf(fp, "%f %f %i", &preSalePrices, &doorPrices, &preSales) != EOF) {
        printf("%f, %f, %i", preSalePrices, doorPrices, preSales);               
    } 
}

我看了所有在互联网上,我无法找到与此相关的任何具体的。

I've looked all over the internet and I can't find anything related to this specifically.

推荐答案

如果你总是知道值的每一行的数量,你可以忽略尾线和读出的值一个接一个。

If you always know the number of values in each line, you can just ignore the end-of-lines and read the values one by one.

如果最终的线是重要的最简单的方法是分别读取每一行(如与fgets ),然后从那里读取数据,并用的sscanf

If the end-of-lines are important the easiest way is to read each line separately (e.g. fgets) and then read the data from there, with sscanf.

这篇关于阅读在C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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