473,549 Members | 5,156 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 16957
Hello,

"Sharon" <sh************ @hotmail.com> wrote in message
news:bs******** ***@news.hgc.co m.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.o rg> ¦b¶l¥ó
news:bs******** ****@ID-161723.news.uni-berlin.de ¤¤¼¶¼g...
Hello,

"Sharon" <sh************ @hotmail.com> wrote in message
news:bs******** ***@news.hgc.co m.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(destina tion, 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.co m.hk...

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

"Sharon" <sh************ @hotmail.com> wrote in message
news:bs******** ***@news.hgc.co m.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_L INE-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"
012345678901234 567890123456789 012345678901
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.o rg> 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 catastrophicall y 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.ne t
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
"constructi ve" as it relates to the phrase "constructi ve 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
10498
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 those changes like this : public static extern uint ExtractIconEx( string szFile,
5
17074
by: Bill | last post by:
Is there any way to programatically extract a cab file using C#? -- Bill Larson
7
7583
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 can't seem to figure it out. Here is what I have so far. p = POP3("mail.server.com")
2
2072
by: vishwa Ram | last post by:
Hi Dears, I want vb code, for extract xml file from Indesign. Thanks, vishwa Ram.
4
1527
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 themes and we must provide it with a file name. Is it possible , knowing the skinid to extract the file name associated in the current theme ? ...
3
3913
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 example "My Data file Apr2007.zip"? In the example below, the parameter pZippedFile contains the file name with spaces and the ...
1
1516
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 %20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton %20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows %20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f...
1
2705
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
1801
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
7455
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7723
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7962
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7480
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7814
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5092
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3504
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1063
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
769
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.