"Umesh" <> ha scritto nel messaggio
news: oups.com...
> /* This is what I can do. If the length of the string starting with
> abc & ending with xyz is known(11 in this case), I can program it as
> follows. But if the length of the string varies between 10 to 50* what
> should I do? Thanks. /
No, it doesn't. "abc45678xyz" doesn't work.
You are only comparing the string with "abc xyz".
>
> //abc?????xyz
> #include<stdio.h>
> #include<stdlib.h>
> int main()
> {
>
> FILE *f,*fp;
> f=fopen("c:/1.txt","r");
> if(f==NULL)
> {
> puts("Error opening file");
Write that to stderr, not to stdout...
> exit(0);
Use EXIT_FAILURE, not 0 which means 'success'...
> }
> fp=fopen("c:/2.txt","w");
Check it for NULL, too.
>
> char c[12];
> while((c[0]=getc(f))!=EOF)
EOF doesn't fit in a unsigned char and might compare equal to a
valid signed char.
see
www.c-faq.com, question 12.1.
> if(c[0]=='a' && (c[1]=getc(f))!=EOF && c[1]=='b' && (c[2]=getc(f))!
> =EOF && c[2]=='c'&& (c[3]=getc(f))!=EOF && c[3]!=' ' && (c[4]=getc(f))!
> =EOF && c[4]!=' ' && (c[5]=getc(f))!=EOF && c[5]!=' ' &&
> (c[6]=getc(f))!=EOF && c[6]!=' ' && (c[7]=getc(f))!=EOF && c[7]!=' '
> && (c[8]=getc(f))!=EOF && c[8]=='x'&& (c[9]=getc(f))!=EOF &&
> c[9]=='y' && (c[10]=getc(f))!=EOF && c[10]=='z')
What a mess...
What's wrong with
scanf("%11c", c);
if (!strcmp(c, "abc xyz"))...
> {
> c[11]='\0';
> fprintf(fp,"%s\n",c);
>
> }
> fclose(f);
> fclose(fp);
Check wheter these succeeded.
> return 0;
>
> }
>
Try:
/*not compiled, not tested*/
#define MAXLINE 16383
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int status;
FILE *infp, *outfp;
char buf[MAXLINE+1];
char *str, *endstr = NULL;
infp = fopen("c:/1.txt", "r");
if (infp == NULL) {
perror("Unable to open input file");
exit(EXIT_FAILURE);
}
outfp = fopen("c:/2.txt", "r");
if (outfp == NULL) {
perror("Unable to open or create output file");
fclose(infp);
exit(EXIT_FAILURE);
}
while (fgets(buf, MAXLINE, infp)) {
endstr = NULL;
(str = strstr(buf, "abc")) && (endstr = strstr(str,"xyz"));
if (endstr != NULL)
fprintf(outfp, "%*s", endstr-str+3, str);
}
status = ferror(infp) || ferror(infp);
if (fclose(infp)) {
perror("Unable to close input file");
status++;
}
if (fclose(outfp)) {
perror("Unable to close output file");
status++;
}
return status ? EXIT_FAILURE : 0;
}