-1

I have a .txt file with "./a.out,file.txt,./a.out2,file2.txt"

How can I store "./a.out", "file.txt", "./a.out" and "file2.txt"?

I was trying to use fgets() and sscanf().

while (fgets(buffer, 80, fp) != NULL) {
    sscanf(line, "%s, %s, %s, %s\n", a, b, c, d);
    printf("a = %s\n", a);
    printf("b = %s\n", b);
    printf("c = %s\n", c);
    printf("d = %s\n", d);
}

[but if i print them out, i will read the whole inline into char* a]

  • 2
    `%s` reads whitespace delimited strings. Use `%[^,]` for comma delimited, instead. Also, be sure to check the return value of `sscanf` before assuming that all 4 strings were actually filled in. – dxiv Sep 29 '20 at 02:40
  • 6
    Why are you scanning `line` if `fgets()` is filling `buffer`? – David Ranieri Sep 29 '20 at 02:44
  • 3
    regarding: `sscanf(line, "%s, %s, %s, %s\n", a, b, c, d);` 1) always check the returned value (not the parameter values) any returned value other than 4 indicates an error occurred. 2) the `%s` needs to have max characters modifier that is one less than the length of the input array. – user3629249 Sep 29 '20 at 02:51
  • the `%s` stops inputting when a 'white space' is encountered. Per your question, the input file has no white space between the data elements. Rather there is a comma between the data elements. strongly suggest reading the whole line with `fgets()` then using `strtok()` for the extraction of each data element – user3629249 Sep 29 '20 at 02:54
  • 1
    Please post a [mcve] so we can reproduce the problem and help you debug it.\ – user3629249 Sep 29 '20 at 02:56
  • `fgets(b, s, fp); sscanf( ., "%s")` is an alternate spelling of `gets()`. There's no point using a size in fgets if you immediately throw it away with sscanf. – William Pursell Sep 29 '20 at 02:58
  • regarding; `sscanf(line, "%s, %s, %s, %s\n", a, b, c, d);` DO NOT place '\n' on the end of the format string. Because this will consume all trailing white space and will not return until a non-white space is encountered. – user3629249 Sep 29 '20 at 02:58
  • @WilliamPursell, the function: `gets()` has been depreciated for years and completely removed from the language several years ago. – user3629249 Sep 29 '20 at 03:03
  • @user3629249 "not return until a non-white space is encountered." is a concern for `scanf()`, not `sscanf()` as the _null character_ stops the scan. The trailing `\n` is not needed, a waste of some CPU cycles, but not a functional problem, – chux - Reinstate Monica Sep 29 '20 at 03:15
  • 1
    @user3629249 Yes, gets() is no longer in the language. I am beginning to believe that raw `"%s"` should be completely disallowed for the same reason. – William Pursell Sep 29 '20 at 12:41

1 Answers1

0

Please look at the following question for how to read in a file to a string: How to read the content of a file to a string in C?. Then you can use strntok() with the delimiter ",".

Emily-TTG
  • 531
  • 3
  • 18