删除c中的一列输入文件并写入输出文件

时间:2017-04-25 12:37:22

标签: c preprocessor

我有一个问题,我想从输入文件中删除第一列并将其写入输出文件。我不知道该怎么做。 我搜索了网站,但找不到我想要的答案。 这是我的输入文件,第一行是标题:

7 11 11
4 5 1 3 2 2 1
2 1 1 3 2 4 1 
5 5 3 4 2 2 2 1 2
3 2 1 3 2 6 2 7 5 
1 1 1 3 3 6 2
6 5 2 4 2 7 6
2 6 6 4 5

我想要的输出文件如下所示:

7 11 11
5 1 3 2 2 1
1 1 3 2 4 1 
5 3 4 2 2 2 1 2
2 1 3 2 6 2 7 5 
1 1 3 3 6 2
5 2 4 2 7 6
6 6 4 5

我怎样才能在C中这样做? 这是我到目前为止所尝试的

int main()
{
FILE *ifp;
FILE *ofp;
char fname[]="input.txt";
char fname2[]="input-v2.txt";
char *mode = "r";
int n;
int m;
int fmt;
ifp = fopen(fname, "r");
ofp= fopen(fname2, "w");
char *token;
char *s=" ";
char line[100000];
if (ifp == NULL)
{
   printf("\nFailed to open file.\n");
    exit(1);
}
fscanf(ifp,"%d %d %d",&n,&m,&fmt);
while (fgets(line, sizeof(line), ifp)) {
    char *copy=strdup(line);
    if(line[0] == '\n')
        continue;
    char *copy=strdup(line);
    if(line[0] == '\n')
        continue;

    token=strtok(copy,s);

    while (token!=NULL && token!=""){
    char *val=token;
    val="";
    fprintf(ofp,"%s",val)
        token=strtok(NULL,s);
    }
      fprintf(ofp, "\n");
}

fclose(ifp);
return 0;
}

我真的不确定该怎么做。我实际上需要从每一行中删除第一个字符,但这个不固定的列号让我感到困惑。

3 个答案:

答案 0 :(得分:1)

代替你的循环你可以使用它 -

token=strtok(copy,s);
token=strtok(NULL,s);              // get complete string after space 
if(token != NULL){
     fprintf(opf, "%s", token); 
}

循环中的一些问题 -

while (token!=NULL && token!=""){
    char *val=token;
    val="";                         // why point val to "" ?
    fprintf(ofp,"%s",&val)          // & is not required with val
    token=strtok(NULL,s);
}

答案 1 :(得分:1)

我发现你帮助谢谢你。这是解决方案:

 while (fgets(line, sizeof(line), ifp)) {
    char *copy=strdup(line);
    if(line[0] == '\n')
        continue;

    token=strtok(copy,s);
    token=strtok(NULL,s);
    while (token!=NULL && token!=""){
        fprintf(ofp,"%s ",token);
        token=strtok(NULL,s);
     }
    fprintf(ofp, "\n");
}

答案 2 :(得分:0)

你没有提到你遇到问题的部分(实际上你到目前为止还没有显示任何代码......)

假设您不知道执行您描述的任务所需的逻辑,我已在下面的伪代码中对其进行了描述

Open(input-file)
if(open failed)
    Return

Open(output-file)
if(open failed)
{
     Close(input-file)
     Return
}

read(first input-file line) // Get the header line but do nothing with it

while(not end of input-file)
{
    string = read(next input-file line)
    if(line not empty && not just new-line)
    {
        find(first character after first space in string)
        write(remainder of string to output file)
    }
}    

Close(output-file)
Close(input-file)

您的示例数据显示第一行标题行不受删除列的影响,因此读入第一行但未使用(由内联注释标记),您可以简单地搜索第一行的结尾,然后在此之后启动while循环。