472,791 Members | 1,193 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,791 software developers and data experts.

C: extract string from file

hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?

I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

Nov 14 '05 #1
9 16848
Hello,

"Sharon" <sh************@hotmail.com> wrote in message
news:bs***********@news.hgc.com.hk...
hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?

I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

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;
Nov 14 '05 #2

"lallous" <la*****@lgwm.org> ¦b¶l„ó
news:bs************@ID-161723.news.uni-berlin.de ¤¤¼¶¼g...
Hello,

"Sharon" <sh************@hotmail.com> wrote in message
news:bs***********@news.hgc.com.hk...
hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T") and extract 35 characters (including "T") from a file and then go to next line?

I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

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)" ??

Nov 14 '05 #3
On Mon, 22 Dec 2003 17:52:04 +0800, "Sharon"
<sh************@hotmail.com> wrote:
I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?


I would use fgets to read a line into a character array. Then I would
string copy the section that I wanted into a second character array.
Something like this might work for you:

char* source="1 This is the string 2 3 4";
char destination[26]={0};
strncpy(destination, source+10, 25);
printf("\"%s\"\n", destination);

The output on my system is:

"This is the string "

Note that you need to make sure that the destination array is null
terminated. I did that in the initialization step.
--

Best wishes,

Bob
Nov 14 '05 #4
Uæytkownik "Sharon" <sh************@hotmail.com> napisa³ w wiadomo¶ci
news:bs***********@news.hgc.com.hk...

"lallous" <la*****@lgwm.org> ¦b¶l„ó
news:bs************@ID-161723.news.uni-berlin.de ¤¤¼¶¼g...
Hello,

"Sharon" <sh************@hotmail.com> wrote in message
news:bs***********@news.hgc.com.hk...
hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T") and extract 35 characters (including "T") from a file and then go to next line?

I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

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)" ??


I think so you didn't keep characters which you read. Your function reading
line of text from file should look like this:

#define MAX_LEN_OF_LINE 256
char line[MAX_LEN_OF_LINE];
int i=0;
memset(line , '\0', sizeof(line));
while (((c=fgetc( file ))!=EOF) && (i<MAX_LEN_OF_LINE-1))
{
if ( c == '\n' ) break;
line[i++]=c;
}

Now you can use strncpy function to extract substring from "line" variable.

Mirek T.
Nov 14 '05 #5

"Sharon" <sh************@hotmail.com> wrote in message

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?
This is rather an awkward line format. If the string can't contain
whitespace you can use the scanf() family of fuctions. Does the string
always start at position 10? Is it always 35 characters long?
I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

OK this is a start. fgets() will read a line from a file for you. Or if you
like you can roll your own.

void readline(char *str, int maxlen, FILE *file)
{
int c;
while ( ( c = fgetc( file ) ) != EOF )
{
maxlen--;
if(maxlen <= 0)
break;
if ( c == '\n' )
break;
*str++ = (char) c;
}
/* add terminating NUL */
*str = 0;
}

(You might want to think about handling error conditions).

Once you've got your line into a string, you can write this function

/*
extract a substring.
in - input string.
out - pointer to output buffer.
start - start position
len - length of substring.
*/
void extract(const char *in, char *out, int start, int len)
{
}
Nov 14 '05 #6
Sharon wrote:

hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?

I know how to go to next line but have no idea how to extract string
thank you for answering!

short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}


This will sound like nit-picking but text files don't have strings in
them. Really. Strings are memory things. Lines are file things. Assuming
you have a file whose first line looks like your example, do something
like this..

char line[256]; /* some too-long number */
.... open the file, etc.
fgets(line, sizeof line, file);

This will read the line from the file and make a string out of it in
line[].

"1 This is the string 2 3 4\n"
012345678901234567890123456789012345678901
1 2 3 4
This is a string because fgets has placed a '\0' in line[41] just past
the '\n'. Note that 'T' is at line[10] but is the eleventh character,
not the tenth. Note also that there are not 35 characters on the line
after the 'T'.
--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #7
In article <bs***********@news.hgc.com.hk>, sh************@hotmail.com wrote:
"lallous" <la*****@lgwm.org> wrote:
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.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 14 '05 #8
On Tue, 23 Dec 2003 03:11:04 GMT, qe*@pobox.com (Paul Hsieh) wrote:
<snip>
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) {
I haven't looked at your version of getline, but I hope here it is
returning a value <= 10, probably < 0 (or 1?), for EOF or I/O error.
If an input error occurs, which is admittedly unlikelyl if that name
accesses a disc file as is likely, this loop will run forever;
fgetstralloc() will keep failing, while !feof(fp) remains true.
You should test ferror(fp) also, and might as well put the tests at
the bottom with do ... while() instead of while() ....
char substr[36];
strncpy (substr, line + 10, 35);
substr[35] = '\0';

printf ("<<%s>>\n", substr);
Aside: if the *only* thing you want to do with a substring is *printf
it, you can just use %.35s with line+10. The OP didn't say that is
what she wanted, although 'extract' *might* mean that.
}
free (line);
}
Curiosity: why is len, whose value is only meaningful per line, local
to the loop body, while line, whose value you make meaningful only per
line although I'm guessing it *could* be otherwise, not?
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) {
The contents of line are undefined if fgets() fails due to I/O error;
in theory this could crash, although in practice it will probably just
be garbage or the last line. Infinitely, as for the one above.
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);
}
Fails catastrophically on an input line less than 10 characters, or
between 45 and (I'm pretty sure) 53 and so on; off-by-one in lines
after the first; produces multiple pieces from lines longer than 53
characters, which I don't think was desired; produces no output at all
from a last (or only) line unterminated by \n on implementations which
support that.
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.
Uh, er, yeah :-)
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);
Again assuming your routines are safe for error or EOF, and again
continues looping forever on error, unless your bgets() exit's or
longjmp's. (And assuming you're not on my rare TNS1-equivalent where
FILE* is different from void* <G>.)
printf ("<<%s>>\n", s->data);
bdestroy (b);
bdestroy (s);
}
fclose (fp);
}

which is probably the easiest solution.


- David.Thompson1 at worldnet.att.net
Nov 14 '05 #9
Dave Thompson <da*************@worldnet.att.net> wrote:
On Tue, 23 Dec 2003 03:11:04 GMT, qe*@pobox.com (Paul Hsieh) wrote:
<snip>
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) {
I haven't looked at your version of getline, but I hope here it is
returning a value <= 10, probably < 0 (or 1?), for EOF or I/O error.


Its written on top of fgetc(), so an error or EOF will be detected and
unified to mean the same thing causing the input line to terminate at
that point.
If an input error occurs, which is admittedly unlikelyl if that name
accesses a disc file as is likely, this loop will run forever;
fgetstralloc() will keep failing, while !feof(fp) remains true.
You should test ferror(fp) also,


Fine, so replace my feof() with (feof(fp) || ferror(fp)). Besides a
mindless bug for a mindless solution, you quoted my entire longish
post just to point this out three more times -- go look up the word
"constructive" as it relates to the phrase "constructive criticism"
(keeping in mind that the OP was trying the learn something, other
than the existence of hardware that became obsolete long before the
existence of USENET.)

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Mohammad-Reza | last post by:
Hi I want to extract icon of an exe file and want to know how. I look at the MSDN and find out that I can use ExtractIconEx() Windows API but in there are some changes to that api in c# I made...
5
by: Bill | last post by:
Is there any way to programatically extract a cab file using C#? -- Bill Larson
7
by: erikcw | last post by:
Hi all, I'm trying to extract zip file (containing an xml file) from an email so I can process it. But I'm running up against some brick walls. I've been googling and reading all afternoon, and...
2
by: vishwa Ram | last post by:
Hi Dears, I want vb code, for extract xml file from Indesign. Thanks, vishwa Ram.
4
by: WT | last post by:
Hello, I am using themes and have seral themes for my site, user can choose it from a list then it is applyed to all pages by program. Problem is that some compoinent we use does not support...
3
by: learningvbnet | last post by:
Hi, I am trying to extract zipped files using Winzip in my VB.net application and I ran into 2 stone walls. 1. How do you handle file names with spaces. See psiProcess.Arguments For...
1
by: josephtys86 | last post by:
203.114.10.66 - - "GET /stat.gif? stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton %20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton...
1
by: Edwin.Madari | last post by:
from each line separate out url and request parts. split the request into key-value pairs, use urllib to unquote key-value pairs......as show below... import urllib line = "GET...
5
by: moroccanplaya | last post by:
i got a program that creates a file then adds a file on top of that file so how would i go on and extract this file? here is my code.
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.