如何在 C 中读取文件时忽略行尾?
How to ignore end of line while reading file in C?
我是 C 语言编程的菜鸟,所以请耐心等待,如果我的方法有误,请指正。
我在用 C 逐字符读取文件时遇到问题。
如下图所示,
显然,我的文件有 400 个字符,但是当我尝试逐个字符地读取它们时,它们最多需要 419 个索引。我猜他们也包括行尾字符。我不知道如何忽略它们。如您所见,我尝试使用 continue
,但我无法忽略它们。
这是我的文件数据
00000000000000000000
00000000000000000000
00000000000000000000
00555555555555555500
00000000000000000300
00000000000000000300
00000000000000000300
00000000000000000300
00000000000000000300
00000000000000000300
00444444444444444300
00400000000000000000
00400000000000000000
00400000000000000000
00400000000000000000
00400000000000000000
00777777777777777700
00000000000000000000
00000000000000000000
00000000000000000000
这是我的代码:
FILE *pToFile = fopen("toConvert.txt", "r");
char single;
i = end_color;
while ((single = fgetc(pToFile)) != EOF) {
if (single != '[=11=]') {
continue;
} else {
if (single !='0') {
bitmap[i] = 0x66;
} else {
bitmap[i] = 0xff;
}
i++;
}
}
注意: 我正在尝试在字符为 0 时在位图中添加 "gray (0x66)" 颜色,在字符不为零时添加 "white 0xff" 颜色.换句话说,我必须区分 0 和任何其他字符,这很难区分行尾字符。
你文件中的换行符是'\n',而'\0'指的是数组的空字符。所以把后者换成前者,'!='改为'=='跳过换行符的read-in。
FILE *pToFile = fopen("toConvert.txt","r");
// single as int (thanks to Weather Vane comment)
int single;
int i = end_color;
while((single = fgetc(pToFile)) != EOF){
if(single == '\n' ){
continue;
}else{
if(single !='0'){
bitmap[i] = 0x66;
}
else{
bitmap[i] = 0xff;
}
i++;
}
}
我是 C 语言编程的菜鸟,所以请耐心等待,如果我的方法有误,请指正。
我在用 C 逐字符读取文件时遇到问题。
如下图所示,
显然,我的文件有 400 个字符,但是当我尝试逐个字符地读取它们时,它们最多需要 419 个索引。我猜他们也包括行尾字符。我不知道如何忽略它们。如您所见,我尝试使用 continue
,但我无法忽略它们。
这是我的文件数据
00000000000000000000
00000000000000000000
00000000000000000000
00555555555555555500
00000000000000000300
00000000000000000300
00000000000000000300
00000000000000000300
00000000000000000300
00000000000000000300
00444444444444444300
00400000000000000000
00400000000000000000
00400000000000000000
00400000000000000000
00400000000000000000
00777777777777777700
00000000000000000000
00000000000000000000
00000000000000000000
这是我的代码:
FILE *pToFile = fopen("toConvert.txt", "r");
char single;
i = end_color;
while ((single = fgetc(pToFile)) != EOF) {
if (single != '[=11=]') {
continue;
} else {
if (single !='0') {
bitmap[i] = 0x66;
} else {
bitmap[i] = 0xff;
}
i++;
}
}
注意: 我正在尝试在字符为 0 时在位图中添加 "gray (0x66)" 颜色,在字符不为零时添加 "white 0xff" 颜色.换句话说,我必须区分 0 和任何其他字符,这很难区分行尾字符。
你文件中的换行符是'\n',而'\0'指的是数组的空字符。所以把后者换成前者,'!='改为'=='跳过换行符的read-in。
FILE *pToFile = fopen("toConvert.txt","r");
// single as int (thanks to Weather Vane comment)
int single;
int i = end_color;
while((single = fgetc(pToFile)) != EOF){
if(single == '\n' ){
continue;
}else{
if(single !='0'){
bitmap[i] = 0x66;
}
else{
bitmap[i] = 0xff;
}
i++;
}
}