How can I read and process this kind of file [clos

2019-09-25 10:16发布

问题:

I 12 0

I 9 1

I 26 0

I 25 2

B 26

P 0

R 25

A

So, what I need to do is read a file containing these characters/numbers and whenever I encounter a letter, I call a function to process whatever comes after the letter (aka the numbers). For example: When reading "I" I have to call the function to INSERT a certain number in a certain level of a Skip List; or when reading B, I need to search for a specific number in the Skip List, etc.

Problem is I'm really bad at reading from a file, can you guys enlighten me?

回答1:

You can do this with file operations in c, i am just giving you hints,

FILE *pFilePtr; // file pointer(handle of file)

pFilePtr = fopen(argv[1],"r"); 

//define buffer to store data read line by line data
char buf[32]={0};

//Now you can run a while loop to read entire file

with fread() to get whole first line(until '\n')

while(!feof(pFilePtr))

{

if(NULL != fgets(buf,32,pFilePtr))

// perform string operation on buffer to extract letters and digits

// and according to that call functions you need

}



回答2:

#include <stdio.h>
#include <string.h>

int main(void) {

    FILE *fptr;
    char mystring[20];
    int number;
    fptr = fopen("Input.txt", "r");

    while(fscanf(fptr , "%s %d", mystring, &number) !=  EOF) {
        printf("%s %d\n", mystring, number);

        if(strcmp(mystring, "I") == 0) { 
            printf("Implement the reqd function here\n");
        }
    }
}


标签: c io