简体   繁体   English

C程序正在编译并运行,但是我在终端中得到了一个奇怪的输出

[英]c program is compiling and running but I am getting a weird output in the terminal

so I have a method that moves a string from a file to a char array in c, but when I try to print it out I am getting a weird output in the terminal that looks like a bunch of for each char spot and each box has 4 0's and 1's. 所以我有一个方法可以将字符串从文件移动到c中的char数组,但是当我尝试将其打印出来时,在终端中出现了一个奇怪的输出,每个字符点和每个盒子都有一堆4个0和1。

Here's the my code: 这是我的代码:

    int main(int argc, char** argv){
            if(argc != 3){
                    printf("not valid # of arguments");
                    return 1;
            }
            struct stat info;
            int status;
            status = stat(argv[2], &info);

            if(status != 0){
                    printf("Error, errno = %d\n", errno);
                    return 1;
            }
            //command line argument is file
            if(S_ISREG (info.st_mode)){
                    printf("%s is a file \n", argv[2]);
                    char *string1;
                    string1  = getFileString(argv[2]);
                    printf("string in file is %s \n", string1);
                    free(string1);
                    return 0;
            }
            if(S_ISDIR(info.st_mode)){
                    printf("%s is a directory \n", argv[2]);
                    openDirRec(argv[2]);
                    //what to do if command line argument is directory
            }
            return 0;


    }
    char* getFileString(char *fileName){
        FILE* qp;
        qp = fopen(fileName, "r");
        char ch;
        struct stat st;
        if(stat(fileName, &st) != 0) {
        return NULL;
        }
        /*int sizeCheck = 0;
        while((ch=fgetc(qp))!=EOF){
                sizeCheck++;
        }
        */
        int sizeCheck = st.st_size;
        if(sizeCheck == 0){
                return NULL;
        }
        else{
                //fseek(qp, SEEK_SET, 0);
                char *fileString;
                fileString = (char*)malloc(sizeof(char) * sizeCheck + 1);
                memset(fileString, 0, sizeCheck + 1);
                //rewind(qp);
                int count = 0;
                while((ch=fgetc(qp)!=EOF)){
                        fileString[count] = ch;
                        count++;
                }
                printf("%s\n", fileString);
                fileString[sizeCheck] = '\0';
                fclose(qp);
                return fileString;

}
}

This line is the culprit. 这是罪魁祸首。

            while((ch=fgetc(qp)!=EOF))

Due to operator precedence, that is equivalent to: 由于运算符优先级,所以等效于:

            while(ch = (fgetc(qp)!=EOF) )

what you need is a little rearrangement of the parantheses. 您需要的是对小括号的重新排列。

            while((ch=fgetc(qp)) != EOF)

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

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