[Solved] Reading a character and a string from a file in C [closed]


(I did that answer while R 0x... and W 0x... was given on the same line rather than two)

If you are sure each line of the file contains R<space>0x...<space>W<space>0x... then you can do

int main()
{
  FILE * fp = fopen("in", "r");

  if (fp == NULL) {
    puts("cannot open 'in'");
    return -1;
  }

  char line[100];

  while (fgets(line, sizeof(line), fp)) {
    char c1, c2;
    unsigned n1, n2;

    errno = 0;
    if ((sscanf(line, "%c %x %c %x", &c1, &n1, &c2, &n2) == 4) && !errno) {
      // just to indicate it read well
      printf("%c:%x:%c:%x\n", c1, n1, c2, n2);
    }
    else {
      printf("invalid line %s\n", line);
    }
  }

  puts("done");
  fclose(fp);
}

Compilation and execution

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra f.c
pi@raspberrypi:/tmp $ cat in
R 0x1 W 0x2
A 0x123 Z 0x345
C 0x0 Z 0x678
pi@raspberrypi:/tmp $ ./a.out
R:1:W:2
A:123:Z:345
C:0:Z:678
done

Note I first read the line to not be disturbed by the newline etc


If you can have several spaces and/or may be tabs between the field and/or even at the beginning of the line you can use strtok :

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

int getChar(char * c, char * s, int n)
{
  if (s == NULL) {
    printf("field %d is missing\n", n);
    return 0;
  }
  if (s[1] != 0) {
    printf("invalid field %d : '%s'\n", n, s);
    return 0;
  }

  *c = s[0];
  return 1;
}

int getUnsigned(unsigned * u, char * s, int n)
{
  if (s == NULL) {
    printf("field %d is missing\n", n);
    return 0;
  }

  char c;

  errno = 0;
  if ((sscanf(s, "%x%c", u, &c) != 1) || (errno != 0)) {
    printf("invalid field %d : '%s'\n", n, s);
    return 0;
  }

  return 1;
}

int main()
{
  FILE * fp = fopen("in", "r");

  if (fp == NULL) {
    puts("cannot open 'in'");
    return -1;
  }

  char line[100];

  while (fgets(line, sizeof(line), fp)) {
    char c1, c2;
    unsigned n1, n2;

    if (getChar(&c1, strtok(line, " \t"), 0) &&
        getUnsigned(&n1, strtok(NULL, " \t"), 1) &&
        getChar(&c2, strtok(NULL, " \t"), 2) &&
        getUnsigned(&n2, strtok(NULL, " \t\n"), 3)) /* warning \n is added */
      // just to indicate it read well
      printf("%c:%x:%c:%x\n", c1, n1, c2, n2);
  }

  puts("done");
  fclose(fp);
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra ff.c
pi@raspberrypi:/tmp $ cat in
 R 0x1   W  0x2
A    0x123 Z 0x345
    C 0x0  Z     0x678
pi@raspberrypi:/tmp $ ./a.out
R:1:W:2
A:123:Z:345
C:0:Z:678
done

2

solved Reading a character and a string from a file in C [closed]