fscanf()返回负值 [英] fscanf() returns negative value

查看:270
本文介绍了fscanf()返回负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fscanf()函数从文本文件中逐行读取数据。它运作正常但突然间我不知道我犯了什么错误,现在函数返回负值。下面是我的代码片段:

I am using fscanf() function to read data line by line from a text file. It was functioning fine but suddenly I don''t know what mistake I made and now the function returns a negative value. below is my code snippet:

FILE *fp;
char ip[16];
int port;

fp = fopen("ClientInformation.txt", "r"); //open the file

//Finding the Size of the file
int size = -1;
fseek (fp, 0, SEEK_END);
size=ftell (fp);

if(size > 0) //proceed only if the file is not empty
   {
      while (fscanf(fp, " %s %d", ip, &port) > 0)
         {
            //scanf() successful
         }
   }





固定代码块[/ edit]

推荐答案

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



代码

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 :)


这篇关于fscanf()返回负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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