[英]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 相反,我建议
fgets()
fgets()
读取一行 int
using strtol()
strtol()
将字符串输入转换为int
Some other suggestions: 其他一些建议:
main()
is int main(void)
. main()
签名是int main(void)
。 fopen()
before using the returned pointer. fopen()
是否成功。 fgetc()
returns an int
. 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.