将文本文件中的字符添加到数组中

时间:2017-09-14 19:26:28

标签: c arrays

我是C的新手,正在尝试完成作业。程序应将文件名作为命令行参数,然后打印文件内容。我的程序打印混乱的文本而不是文件中的实际文本。

我已经在互联网上搜索了我的问题的示例/答案并且仍然卡住了!

我做错了什么?如果可以提供帮助,请修改我的代码而不是编写新代码,以便我更容易理解。

int main()
{
    char fileName[20];
    int *buffer;
    int size;

    // ask for file name and take input.
    printf("Enter file name: ");            
    scanf("%s", fileName);

    // open file in read mode.
    FILE *fp;
    fp = fopen(fileName, "r");          

    // If no file, show error.
    if(fp == NULL)                  
    {
        printf("Error: Can't open file.\n");        
        return 1;
    }

    // count characters in file with fseek and put into size, then move the
    // position of the file back to the beginning.
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    rewind(fp);

    // allocate buffer and read file into buffer.
    buffer = malloc(size+1);
    fread(buffer, 1, size, fp);

    // close the file.
    fclose(fp);

    // for loop reading array one character at a time.
    for(int x = 0; x < size; x++)
    {               
        printf("%c", buffer[x]);
    }

    return 0;
}

1 个答案:

答案 0 :(得分:2)

您使用错误的数据类型来读取字符,即使用int *buffer,但您应该使用char *buffer

使用int *buffer时,像printf("%c",buffer[x])这样的访问将作为整数数组访问缓冲区;一个整数的大小可能是4,这样buffer[1]解决了缓冲区中的第4个字节,buffer[2]解决了第8个等等...因此,你会读出不是包含在文件中,实际上超出数组边界(导致垃圾或其他)。