简体   繁体   English

从C中的文本文件读取整数

[英]reading integers from text file in c

I want to read a text file where image pixels values are stored in this fashion 我想读取一个以这种方式存储图像像素值的文本文件

234
23
176
235
107
187
201
128
147
...
....
..

I tried to read this text file in this manner 我试图以此方式阅读此文本文件

#include<stdio.h>
#define M 2500
int main()
{

unsigned  new_img[M];
unsigned char a;
FILE *input;
input=fopen("D:/trail.txt","r");
for(i=0;i<M;i++)
{
    a=fgetc(input);
    new_img[i]=(int)a; 
    input++;
}
....

....

...
return 0;
}

when I tried it to print it showing some random values. 当我尝试打印时显示一些随机值。 Also, all my pixels values are in the range of 0 to 255. But at the output screen I am getting values as large as 1 to 1 million 此外,我所有的像素值在0至255,但在输出画面我得到的值大到1 100万

As per the man page of fgetc() , we can see 根据fgetc()手册页 ,我们可以看到

fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error. fgetc()从流中读取下一个字符,并以无符号字符的形式将其返回给int,或者在文件或错误结束时返回EOF。

it reads character-by-character in lexicographical way, not based on the value . 它以字典方式而不是根据value 逐字符读取字符

Instead I suggest 相反,我建议

  • read a line using fgets() 使用fgets()读取一行
  • convert the string input to int using strtol() 使用strtol()字符串输入转换为int
  • store it into the array. 将其存储到数组中。

Some other suggestions: 其他一些建议:

  1. The recommended signature of main() is int main(void) . 推荐的main()签名是int main(void)
  2. Always check for the success of fopen() before using the returned pointer. 在使用返回的指针之前,请始终检查fopen()是否成功。
  3. FWIW, fgetc() returns an int . FWIW, fgetc()返回一个int You should collect the return value in an int variable, ideally. 理想情况下,您应该将返回值收集在int变量中。

Note: you need to take care of the trailing \\n read by fgets() and error checking for the validity of input. 注意:您需要注意fgets()读取的尾随\\n ,并检查输入的有效性并进行错误检查。

You are using fgetc() , which is not the right way to read integers, and also doing it wrong. 您正在使用fgetc() ,这不是读取整数的正确方法,而且做错了。 Notice that its return type is int , since it can return the constant EOF . 注意,它的返回类型为int ,因为它可以返回常量EOF You're truncating the return value into an unsigned char , which makes no sense. 您正在将返回值截断为unsigned char ,这没有任何意义。

It reads characters , so for an input string of eg 234 , you would first see the character 2 , then 3 , then 4 , then the line feed character(s), and so on. 它读取字符 ,因此对于例如234的输入字符串,您将首先看到字符2 ,然后是3 ,然后是4 ,然后是换行字符,依此类推。 Not what you want. 不是你想要的。

You should just use: 你应该只使用:

int pixel;

if(fscanf(input, "%d", &pixel) == 1)
{
  printf("read pixel %d\n", pixel);
}

This converts a decimal integer (which can consist of many individual characters), and writes the integer into pixel . 这将转换一个十进制整数(可以包含许多单独的字符),并将该整数写入pixel If it fails, it won't return 1 . 如果失败,则不会返回1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM