存储和消除垃圾值

时间:2014-03-06 01:25:57

标签: c arrays store

每当我尝试运行代码时,它都会打印出文件的内容,但是它会在最后打印出一个我不知道如何摆脱的垃圾值。我应该将文件的内容存储到一个数组中,但是我对如何做到这一点有点困惑?

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

char filePrinter(char*arr)

int main (int argc, char**argv)
{
    char fileArray[150];

    if(argc !=2)
    {
        printf("Invalid Entry. Please Enter name of program followed by input filename\n");
    }

    filePrinter(fileArray);

    return 0;
}

char filePrinter(char*arr)
{
    int i;
    FILE*file;
    i=0;

    file=fopen("assests/room.txt","r");
    if(file == NULL)
    {
        printf("Could not open file\n");
        exit(-1);
    }
    else
    {
        while(0 ==feof(file))
        {
            i=fgetc(file);
            printf("%c", i);
        }
    }
    fclose(file);
    return i;
}

文件内容:

10x16 ds5 h6,5 g7,8 p3,3
10X16 de4 h5,7 g9,2
10X16 dw6,h2,3 m6,7
10X16 dn3,h2,4 p2,3
10X16 de2 h9,9 m4,5
10X16 dn8 h4,5 g1,1*/

3 个答案:

答案 0 :(得分:0)

由于feof EOF出现fgetc,因此定时比查看循环开头时要糟糕。

替换为

while(EOF!=(i=fgetc(file))){
    printf("%c", i);
}

int filePrinter(char*arr){
    int i = 0, ch;
    FILE*file;

    file=fopen("assests/room.txt","r");
    if(file == NULL) {
        printf("Could not open file\n");
        exit(-1);
    } else {
        while(EOF!=(ch=fgetc(file))) {
            //printf("%c", ch);
            arr[i] = ch; //*arr++ = ch;
            ++i;//i : range check
        }
        arr[i] = '\0';
    }
    fclose(file);
    return i;
}

答案 1 :(得分:0)

如果 last 调用read操作命中EOF,

feof将返回true。你想在fgetc电话后测试它。或者,更好的是,只需检查fgetc是否返回了特殊值EOF

(A FILE *有一个“文件结束标记”,表示某些读取操作是否已达到EOF。读取操作会在达到EOF时设置“文件结束标记”。 hit ---意思是试图读过去---文件的结尾,“文件结束标记”很清楚。)

答案 2 :(得分:-1)

我认为代码应该是:

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

void filePrinter(char*arr);  

int main (int argc, char**argv)
{
    char fileArray[150];
    memset(fileArray, 0, sizeof(fileArray));

    if(argc !=2)
    {
        printf("Invalid Entry. Please Enter name of program followed by input filename\n");
    }

    filePrinter(fileArray);

    return 0;
}

void filePrinter(char *arr)
{
    int c = 0, j = 0;
    FILE* file = NULL;

    file=fopen("assests/room.txt","r");
    if(file == NULL)
    {
        printf("Could not open file\n");
        exit(-1);
    }
    else
    {
        while (1)
        {
            c = fgetc(file);
            if (c != EOF)
            {
                  arr[j++] = c;
            }
            else
            {
                break;
            }
        }
    }
    fclose(file);
    return;
}