在文本文件中搜索字符串,用空格分隔并在空格后切掉所有内容

问题描述 投票:0回答:1

我想在每行之间用空格分隔字符串之后切断文本文件中的所有内容,因此,例如,如果文本文件包含行:

I am a String.
Iam a String too.

在输出文件的第一行中,输出文件中只有I,而在第二行中,该行的左边仅Iam

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    FILE *input,*output;
    char line[40];
    if(argc == 3){
        input = fopen(argv[1],"r");
        output = fopen(argv[2],"w");
        if(input!= NULL){
                while(!feof(input)){
                    fgets(line,sizeof line,input);
                    strtok(line," ");                    
                    fputs(line,output);                  

                }
                fclose(input);
                fclose(output);
        }
    }
}

这几乎是completeley的工作方式,尽管它使彼此之间的更多行混淆:/

c string
1个回答
0
投票

您想要这样的东西:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
  if (argc != 3)
  {
    display error message
    return 1;
  }

  FILE *infile = fopen(argv[1], "r");  // Use "r", not 'w'.
                                       // Use consistant variable naming: infile and outfile
  if (infile == NULL)                  // file could be opened?
  {
    display error message
    return 1;
  }

  FILE *outfile = fopen(argv[2], "w");   // Use "w", not 'a'
  if (outfile == NULL)                   // file could be opened?
  {
    display error message

    fclose(infile);                   // close infile that is obviously open here
    return 1;
  }

  do
  {
    char line[1000];

    if (fgets(line, sizeof line, infile) == NULL)   // read complete line
      break;                                        // enf of file : stop loop

      process line

      fputs(line, outfile);                         // write line
  } while (1);

  fclose(infile);
  fclose(outfile);
}

仍有代码供您编写。这段代码中可能有错误,但是您应该了解一下。

© www.soinside.com 2019 - 2024. All rights reserved.