且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

fscanf()返回负值

更新时间:2023-02-19 23:19:59

这是一个不做事情的好例子。它以帖子标题中的基本单词中的拼写错误开头。您在此处提供的代码没有合理的缩进。最重要的是,您正在演示糟糕的编程技术。查找文件长度的方法比在其内容上执行逐个字符循环更简单。如果您使用过其中一个,那么首先你不会遇到问题。



代码

This is a good example of how NOT to do things. It starts with a typo in the essential word in the title of your post. The code you presented here has no reasonable indenting. And foremost, you are demonstrating bad programming techniques. There are easier methods of finding the length of a file than doing a character-by-character loop over its contents. If you had used one of those, you wouldn''t have run into your problem in the first place.

The code in
if(size > 0)
{
    while (fscanf(fp, " %s %d", ip, &port) > 0)
    {
        MessageBox (NULL, "fscanf() Successful", "SUCCESS!",
            MB_ICONINFORMATION);
    }
}



可能更简单。外部if构造完全没用。你的while循环将涵盖文件无论如何都是真实的情况。因此,实际上没有必要在第一步中确定文件长度。



如果您只花20分钟在代码中找到问题,为什么呢?你发布了这个问题吗?我本以为你在发布问题之前已经考虑了很多想法。


could be much simpler. The outer if-construct is totally useless. Your while loop will cover the case that the file is emply anyway. So, there is actually no need to determine the file length in the first step.

If it took you just 20 minutes to find the problem in your code, why did you post the question at all? I would have expected that you took so much thought before even posting a question.


[这篇文章不是答案,应该删除 - SA]



在fscanf()解决问题之前添加倒带(fp):)
[This post is not an answer and should be removed — SA]

Adding rewind(fp) just before fscanf() solved the problem :)