首页 > 解决方案 > 如何使用strtok和指针读取txt文件并逐行逐字分割?

问题描述

我想读取数据 5 行到最后一行。

strtok我已经使用函数逐行完成了,我将使用strtok但没有工作。

ptr21 result andptr`是一样的:我该怎么办?我的目标是 struct -> 202001 ~ 167~236

数学.txt:

course name : Mathematics
Instructor : Mannan

ID  NAME    MID PROJECT FINAL   TOTAL
202001  s1  46  54  67  167
202002  s2  87  93  88  268
202004  s4  26  48  56  130
202006  s6  93  89  90  272
202007  s7  65  75  80  220
202008  s8  58  49  43  150
202010  s10 85  78  76  239
202012  s12 76  85  81  242
202013  s13 54  74  69  197
202014  s14 73  79  84  236

我的代码:

#define _CRT_SECURE_NO_WARNINGS
#define STRING_SIZE 256

#include <stdio.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>

struct test_result { 
    int ID; 
    char NAME[10]; 
    int MID; 
    int PROJECT; 
    int FINAL; 
    int TOTAL; 
    float numeric; 
}; 

int num_students = 0; 

int main(void) {
    system("Cls");
    char answertype;
    FILE* f1= NULL;
    FILE* f2 = NULL;
    FILE* f3 = NULL;
    printf("\n\n\n");
    f1 = fopen("Math.txt", "r");
    f2 = fopen("Science.txt", "r");

    int linecount = 1;
    if (f1 != NULL)
    {
        int size;
        char *buffer;
        fseek(f1, 0, SEEK_END);   
        size = ftell(f1);//size of buffer
        buffer = malloc(size + 1);
        fseek(f1, 0, SEEK_SET);  

        while (!feof(f2))
        {
            fgets(buffer, 34, f2);
            linecount++;
            char* ptr= strtok(buffer, " ");
            while (ptr != NULL && linecount > 5)//3 instruct 2 subject
            {
                if (ptr != "course")
                {
                    //printf(" %s", ptr);

                    struct test_result p1;
                    char* ptr2 = strtok(ptr, " ");
                    while (ptr2 != NULL)            
                    {
                        printf("%s", ptr2);          
                        ptr2 = strtok(NULL, " ");      
                    }
                    ptr = strtok(NULL, " ");
                }   
            }
        }
        free(buffer);
        fclose(f1);
        fclose(f2);
        fclose(f3);
        return 0;
    }
}

标签: cpointersstrtok

解决方案


推荐阅读