How to use fgets to read a file line by line

前端 未结 3 1361
庸人自扰
庸人自扰 2021-01-25 04:21

I\'m new at programming so there are some basics and maybe common sense that I don\'t know. I have a question about how to use fgets right. Based on the explanation of fgets, it

3条回答
  •  生来不讨喜
    2021-01-25 05:04

     #include 
    
     int main()
     {
        char str[150],str2[100][150];
        int i=0,j=0,value[100];
        FILE* fp;
        fp = fopen("file.txt", "r");
        while (fgets(str,150, fp)) {
            i++;
            printf("%3d: %s\n", i, str);
            /** if you want to split value and string*/
            sscanf(str,"%s %d",&str2[j],&value[j]);
            printf("%d %s\n",value[j],str2[j]);
            j++;
        }
        fclose(fp);
        return 0;
    }
    

提交回复
热议问题