简体   繁体   中英

C reading formatted text from file

i have a question on a C program that I'm doing. The beginning of the track ask this:
"Process P ask as argument the path of a file in which every line ust be 16 characters length (included the end of line), and every line must start with "WAIT" or "NOWAIT" followed by a command."
The example of input file is:

WAIT ls
NOWAIT who
WAIT date

I made this code for now:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#define MIN_SIZE 5
#define ROW_LEN 17
int main (int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Program usage: %s file_path.\n", argv[0]);
        exit(1);
    }
    
    int fd = open(argv[1], O_RDONLY);
    struct stat fd_info;
    
    if(fd < 0) {
        perror("Error opening file");
        exit(2);
    }
    
    
    fstat(fd, &fd_info);
    if(fd_info.st_size <= MIN_SIZE) {
        printf("Size of file '%s' is less or equal than 5 bytes.\n", argv[1]);
        exit(3);
    }
    
    char buf[ROW_LEN];
    buf[ROW_LEN - 1] = '\0';
    while ((read(fd, buf, ROW_LEN - 1)) > 0) {
        char type[ROW_LEN], cmd[ROW_LEN];
        sscanf(buf, "%s %s", type, cmd);
        printf("type=%s; command=%s;\n", type, cmd);
    }
    
    
    return 0;
}

In this way i can read good only if in the file.txt I complete every row with spaces until it reaches 15 characters for each line (else it start reading next line too). But in the file that prof gave us there aren't spaces to complete the row. So my question is, how can I read correctly from the file? I can't understand that "every line must have 16 characters included end of line". Thanks to all, I hope I explained good the question!

Firstly with this sentence you must considerate each line as a possible input, but the input is coming from anyone so anything can append and any errors in consequences.

You start on the good way you must consider all your file and after your line > check if your line is good

you can use getline to get your file easily, and strlen and strcmp to check if your line is conform.

Finaly the part "include end of line", that mean that all the line must have a length of 16 character with '\0', so in your file the "visible" length must be at 15 for the maximum,

for example if the maximal length is 3 included end of line: "abc": incorrect because it's equal to {'a', 'b', 'c' '\0'}; "ab": correct because it's equal to {'a', 'b', '\0'};

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