如何将文件打印到屏幕上?

时间:2015-04-24 19:52:39

标签: c file

我正在尝试从quiz_scores.txt获取数据以打印到屏幕上,以便我可以将其扫描到数组中,但我不知道如何。我是否需要将文件硬编码到我的程序中,如果是这样的话?

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

int main(void)
{
    //initializing variables

    FILE *es;
    FILE *hs;
    int num=0;
    int i;
    int j;
    int cols=10;
    int rows=10;
    int qid, s;
    int quizarray[0][0];
    int MAX_LENGTH=15;
    char *result0;
    char line[MAX_LENGTH];
    FILE *qs="C:\\quiz_scores.txt";

    qs = fopen("quiz_scores.txt", "r");

    /*for (i=0; i<cols; i++){
        for (j=0; j<rows; j++){
            quizarray[i][j]=0;
            fscanf(qs, "%d%d", quizarray[i][j]);
        }
    }
*/ 
    while(fgets(line, MAX_LENGTH, qs))
    {
        printf("%s", line);
    }
    if(qs == NULL)
    {
        printf("Error: Could not open file\n");
        return -1;
    }
    /*for (i=0;i<n;i++)
    {
        fprintf(qs, "%d\n");
    }
    fclose(qs);*/
    return 0;
}

1 个答案:

答案 0 :(得分:0)

OK I think I know what you want to happen, read numbers from the file quiz_scores.txt into your 2d array and print them,correct?. I hope these corrections will allow you to do just that and also that you will understand why it wouldn't work before. The rest of the program is for you to do yourself, good luck!!

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

int main(void)
{
    //initializing variables
    int num=0,i,j,cols=10,rows=10;//just smooshed all onto the same line cause it was annoying me
    int quizarray[10][10];//You declared a 2d array with 0 elements(you wanted one with ten rows and columns I presume 10 teams 10 rounds)
    FILE *qs = fopen("quiz_scores.txt", "r");//Your declaration of the file pointer was incorrect
    if(qs == NULL)//This if needs to go before you read anything from the file otherwise its kind of redundant
    {
        printf("Error: Could not open file\n");
        return -1;
    }

    for (i=0; i<cols; i++)
    {
        for (j=0; j<rows; j++)
        {
            quizarray[i][j]=0;
            fscanf(qs,"%d", &quizarray[i][j]);//Them scanfs need &s mate  
            \\and don't try to scan in two integer into one array element
            printf("%d",quizarray[i][j]);
            if(j<rows-1)
                printf("-");
        }
        printf("\n");
    }

    fclose(qs);//Dont comment fclose out bad things will happen :P
    return 0;
}