简体   繁体   中英

Reading a text file and ignoring commented lines in C

I'm currently working on making a tiny computer in C for a programming assignment and I'm stuck on one part.

I'm stuck on how to correctly ignore comments in a text file that I'm reading in. (Example of file input below).

Input File
5 5     //IN 5
6 7     //OUT 7
3 0     //STORE 0
5 5     //IN 5
6 7     //OUT 7
3 1     //STORE 1
1 0     //LOAD 0
4 1     //SUB 1
3 0     //STORE 0
6 7     //OUT 7
1 1     //LOAD 1
6 7     //OUT 7
7 0     //END

The first input on each new line is an operation, the 2nd input being an address. I am planning to have a switch statement for each op and then calling the appropriate function. This is my current layout for reading in the file:

//file handling
int c;
FILE * file;
file = fopen(name, "r");
if (file){
    printf("Run.\n");
    while ((c = getc(file)) != EOF){
        op = c;
        switch (op){
            case 5:
                print("Inside case 5\n");
        }
    }
    fclose(file);
}

How can I ignore the // on each line and skip to the next line in the file?

Call fgets to get a full line:

fgets(buffer, 100, file);

and then extract the two numbers from the line:

sscanf(buffer, "%d%d", &instruction, &address);

how to correctly ignore comments in a text file that I'm reading in
How can I ignore the // on each line and skip to the next line in the file?

Read the line using fgets()

char buf[80];
if (fgets(buf, sizeof buf, file)) {

Look for the // with strstr() @Steve Summit and lop off the string at that point.

  char *slash_slash = strstr(buf, "//");
  if (slash_slash) {
    *slash_slash = '\0';
  }

Continue processing the line as desired.

  ...
}

By using fgets and strtok you can read line by line and split the string acording to the // delimiter. Here's an example (it is not fully checked, but it's the main idea):

FILE *f = fopen("file.txt", "r");
    if (f== NULL)
    {
        printf("opening file failed\n");
        return 1;
    }
    char buf[256] = { 0 };
    while (fgets(buf, 256, f))
    {
        char *s = strtok(buf, "//");
        if (s == NULL)
        {
            printf("s == NULL\n");
        }
        else
        {
            printf("%s\n", s);
        }
        memset(buf, 0, 256);
    }
    fclose(f);

EDIT: I just realized that this is not exactly what you were looking for. However, you can still use it in order to first ignore the comment, and then break the given string into operation and address, or whatever that is...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM