从作为命令行参数传递的文件中读取 [英] Reading from files passed as command line arguements

查看:197
本文介绍了从作为命令行参数传递的文件中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析给定的文本文件,但是到目前为止,我的程序似乎无法正确读取.

I am trying to parse a given textfile, but so far, my program does not seem to be reading properly.

#include <stdio.h>


int main(int argc, char *argv[])
{
    FILE *fr; //file pointer
    int buildingFloors = 1;

    printf("sanity check\n");  

    fr = fopen (argv[0], "r");
    fscanf(fr, "%d", &buildingFloors );

    printf("%d\n", buildingFloors);

    fclose(fr);

    return 0;
}

我编译该程序,并使用以下命令在我的redhat linux机器上运行它:

I compile the program and run it on my redhat linux machine with the following command:

./sjf file.text

file.text是一个文本文件,第一个字符为"4".所以我希望我的输出是

file.text is a text document with a "4" as the first character. So I would expect my output to be

sanity check
4

但是,当我运行程序时,我却得到了

However, when I run my program I instead get

sanity check
1

这暗示fscanf没有正确读入第一个字符-4.我是否遇到某些语法错误,从而阻止了预期的代码功能?我应该先扫描一个字符,然后以某种方式将其转换为int吗?

Which implies that fscanf didn't properly read in the first character -- 4. Do I have some syntax error that's preventing the expected code functionality? Am I supposed to scanf for a character, and then convert that to an int somehow?

推荐答案

立即想到的一件事是程序args包含可执行文件名称作为第一个元素

One thing which immediatly comes to mind is that the program args include the executable name as the first element

argv[0]是"sjf"

argv[1]是"file.text"

argv[1] is "file.text"

所以您应该使用

fr = fopen (argv[1], "r");

请记住在调试时始终尝试缩小问题范围,如果您知道错误的位置,则原因通常变得很明显或至少可以调查.

Remember when debugging to always try and narrow the problem down, if you know the location of the error the cause often becomes obvious or at least investigatable.

在这种情况下,您应该检查argc >= 2,打印出argv[1]以确保尝试打开正确的文件,然后还检查文件是否已成功打开.

In this case you should check argc >= 2, print out argv[1] to ensure you are trying to open the right file, then also check that the file was opened successfully.

最后检查fscanf错误代码以查看fscanf能够读取该号码.

Finally check the fscanf error codes to see that fscanf was able to read the number.

这篇关于从作为命令行参数传递的文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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