Reputation: 9098
I want to read a line from file in C. Eg in file I have following data
"It was a good
day
but suddenly
everything"
Rightnow, my code just reads line by line but as mentioned in above example I want to read data from the starting inverted commas (") till the ending inverted commas (") and then write that whole string (like "It was a good day but suddenly everything") into another file. i only need help in reading these above lines from starting inverted commas till ending inverted commas. Please guide me which functions in C will help me to do that.
Rightnow, I am just reading data line by line
FILE *file = fopen ( filename, "r" );
if (file != NULL )
{
char line [1000];
while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */
{
//do something
}
}
Upvotes: 0
Views: 2615
Reputation: 40145
#include <stdio.h>
char *read_quoted_string(char outbuff[], FILE *fp){
int ch, i;
while(EOF!=(ch=fgetc(fp)))
if(ch == '"') break;
for(i=0;EOF!=(ch=fgetc(fp));++i){
if(ch == '"') break;
outbuff[i] = ch;
}
outbuff[i]='\0';
return outbuff;
}
int main(void){
FILE *file = fopen("data.txt", "r" );
if (file != NULL ){
char buff [1000];
printf("%s", read_quoted_string(buff, file));
fclose(file);
}
return 0;
}
Also repeats
if (file != NULL ){
int i=1;//sequence number
char buff [1000];
while(*read_quoted_string(buff, file)){//empty is "" (*"" == '\0')
printf("%2d:%s\n", i++, buff);
}
fclose(file);
}
Upvotes: 3
Reputation: 107121
You can use the following code to do this:
#include <stdio.h>
void copyToAnother(FILE *inFile, FILE *outFile)
{
int ch, flag = 0;
while(EOF!=(ch=fgetc(inFile)))
{
if(ch != '"' && toggle)
{
fputc(ch,outFile);
}
else
{
toggle = toggle ^ 1;
}
}
int main(void)
{
FILE *inFile = fopen("in.txt", "r" );
FILE *outFile = fopen("out.txt", "w" );
if (inFile != NULL && outFile != NULL)
{
copyToAnother(inFile, outFile);
fclose(inFile);
fclose(outFile);
}
return 0;
}
Note: In this code. It'll write all the data between all " ".
Upvotes: 1
Reputation: 17595
You may want to use fgetc to read one character at a time:
"
start saving next chars into the buffer"
'\0'
"
in the same line then just don't save '\r'
and '\r'
and save a simple space ' '
instead.fgetc
return EOF
.Upvotes: 2
Reputation: 71
You could just use 'strcat' to concatenate your arrays of chars. See that post for a good example : How do I concatenate const/literal strings in C?.
Upvotes: 0