0

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
     }
    }
4

4 回答 4

3
#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;
}

也重复

    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);
    }
于 2013-06-12T18:44:52.127 回答
2

您可能希望使用fgetc一次读取一个字符:

  • 分配足够大的缓冲区
  • 开始逐字符读取文件
  • 如果您发现"开始将下一个字符保存到缓冲区中
  • 继续保存到缓冲区中,直到到达另一个"
  • 用 a 终止你的字符串'\0'
  • 如果您需要删除新行并将两个字符之间"的所有字符放在同一行中,那么不要保存'\r''\r'保存一个简单的空格' '
  • 重复直到你用完洞文件,即fgetcreturn EOF
于 2013-06-12T18:46:18.133 回答
1

您可以使用以下代码来执行此操作:

#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;
}

注意:在此代码中。它将写入所有“”之间的所有数据。

于 2013-06-12T19:04:52.940 回答
0

你可以只使用'strcat'来连接你的字符数组。请参阅该帖子以获取一个很好的示例:如何在 C 中连接 const/literal 字符串?.

于 2013-06-12T18:38:51.053 回答