Reading from files passed as command line arguements

折月煮酒 提交于 2019-12-02 01:37:47

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.

argv[0] is the name of the program (./sjf in your case), so you're trying to read in your own program's executable. Use argv[1] instead to get the first real program argument.

Your code looks clear and straight-forward, but there is one important thing missing: error handling.

What happens if the file you want to open does not exist? fopen returns NULL in that case.

What happens if the file does not start with a number? fscanf returns the number of fields that have been successfully read, so you should check that the return value is at least 1.

You need to somehow handle these cases, probably by printing some error message and exiting the program. When you do that, be sure to include the relevant information in the error messages. Then you will find the bug that the other answers have already mentioned.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!