lallous said:
If your read string was: "1 This is the string 2 3 4" you
can parse it using strncpy() as:
char str[100];
strncpy(str, line+10, 35);
str[35] = 0;
sorry, I don't understand
how to get the value of "line" ?
e.g. using functions like "fgetc( file)" ??
The common suggestion which is equivalent to the loop around fgetc() ideas
posted here is to use fgets() to get each line. For technical reasons one
might use a getInput()-style function instead, which you can find here:
http://www.pobox.com/~qed/userInput.html . So using a getInput function its
something like:
FILE * fp = fopen ("name_of_file.txt", "rb");
if (fp) {
char * line;
while (!feof (fp)) {
line = NULL;
int len = fgetstralloc (&line, fp);
if (len > 10) {
char substr[36];
strncpy (substr, line + 10, 35);
substr[35] = '\0';
printf ("<<%s>>\n", substr);
}
free (line);
}
fclose (fp);
}
Otherwise if you just want to use fgets ... either life gets really really
difficult or you can implement a "truncated line" solution and hope for the
best:
#define MAX_LINE_SIZE (192)
FILE * fp = fopen ("name_of_file.txt", "rb");
if (fp) {
char line [MAX_LINE_SIZE];
while (!feof (fp)) {
/* This will just screw up if you have a line of > 192
characters and fixing it is annoying. Also this
comment will be out of data when you change
MAX_LINE_SIZE. */
fgets (line, MAX_LINE_SIZE, fp);
if (strlen (line) > 10) {
char substr[36];
strncpy (substr, line + 10, 35);
substr[35] = '\0';
printf ("<<%s>>\n", substr);
}
}
fclose (fp);
}
Of course, if you wanted to do a completely incremental approach (whose ideas
are not really reusable as you try to solve more complex problems) then you
could just do this:
FILE * fp = fopen ("name_of_file.txt", "rb");
if (fp) {
char str[36];
int s = 0;
int c;
while (EOF != (c = fgetc (fp)) {
if (c == '\n') {
str[s-10] = '\0';
printf ("<<%s>>\n", str);
s = 0;
}
if (s >= 10) {
if (s < 35 + 10) str[s-10] = c;
else if (s == 35 + 10) {
str[35] = '\0';
printf ("<<%s>>\n", str);
s = 0;
}
}
s++;
}
fclose (fp);
}
But this solution is a little bit complicated and may need some debugging to
make sure it works properly. Documenting it might be a little difficult as
well.
Another expressive way of doing this is to use a string library which is likely
to contain useful facilities for this purpose. One example is to use "the
better string library" (
http://bstring.sf.net):
FILE * fp = fopen ("name_of_file.txt", "rb");
bstring b, s;
if (fp) {
while (!feof (fp)) {
s = bmidstr (b = bgets ((bNgetc) fgetc, fp, '\n'), 10, 35);
printf ("<<%s>>\n", s->data);
bdestroy (b);
bdestroy (s);
}
fclose (fp);
}
which is probably the easiest solution.