fgetc给我垃圾 [英] fgetc giving me garbage

查看:36
本文介绍了fgetc给我垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的程序,将文本从ASCII文件输出到命令行,但是我又收到了垃圾字符.这里是我的代码的相关部分:

I wrote a simple program to output text from an ASCII file to the command line, but I am getting garbage characters back. Here the relevant bit of my code:

void main(int argc, char *argv[]) {
    char *filename;
    ... [filename is defined here as the command-line argument]
    FILE *fptr = fopen(filename, "r");
    if (fptr == NULL) {
        printf("Error: no such file %s!\n", filename);
        exit(1);
    } else {
        int c;
        while(c = fgetc(fptr) != EOF) {
            putchar(c);
        }
        fclose(fptr);
    }
}

当我使用一个包含一行文本的简单测试文件运行此代码时,我会得到一堆垃圾符号.

When I run this code using a simple test file which contains a line of text I get a bunch of garbage symbols back.

推荐答案

运算符!= 的优先级高于运算符 = ,因此变量 c 被分配了比较值( fgetc(fptr)!= EOF ).要解决此问题,您必须在作业周围加上括号:

Operator != has precedence over operator =, so your variable c is being assigned with the value of the comparison (fgetc(fptr) != EOF). To fix that you have to put parenthesis around the assignment:

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

int main(int argc, char ** argv)
{
    assert(argc == 2);
    FILE * fptr = fopen(argv[1], "r");
    assert(fptr);
    int c;
    while((c = fgetc(fptr)) != EOF) putchar(c); 
    fclose(fptr);
    return 0;
}

(请注意,我断言这些值只是出于可读性.由于您的程序与用户进行交互,因此您可以通过手动检查它们并打印特定的错误消息来做得很好.)

(Note that I asserted the values just for the sake of readability. Since your program interacts with the user, you are doing fine by manually checking them and printing specific error messages.)

这篇关于fgetc给我垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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