Reading from files passed as command line arguements

前端 未结 3 2027
暗喜
暗喜 2021-01-21 16:15

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

#include 


int main(int argc, char *argv[])
{         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 16:33

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

    argv[0] is "sjf"

    argv[1] is "file.text"

    so you should be using

    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.

    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.

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

提交回复
热议问题