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

标签 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;
}

最佳答案

好吧,我想我知道你想要发生什么,将文件 quiz_scores.txt 中的数字读取到你的二维数组中并打印它们,对吗?我希望这些更正能让您做到这一点,并且您会理解为什么它以前不起作用。剩下的程序就由你自己完成了,祝你好运!!

    #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;
}

关于c - 如何将文件打印到屏幕上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29856294/

相关文章:

c++ - 如何将文本文件复制到另一个文件?

python 子进程正在覆盖用于 stdout 的文件 - 我需要它附加到文件 (windows)

c - 下面给出的代码是错误的吗?

python - 在附加模式下,我的文件是否在 RAM 中打开?

java - Android读入与app打包的.txt文件

c - 这个代码片段有什么问题

python - Popen错误: bytes-like object is required,而不是 'str'

c - 具有位域的结构的内存布局

c - 64 位 native 类型原子性和内存总线?

c++ - 有没有更简洁的方法来公开测试的实现细节?