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

remove a column of input file in c and write to output file

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

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

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

你没有提到你的哪一部分有问题(事实上你根本没有显示你到目前为止的任何代码......)

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

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)

您的示例数据显示第一行 header 不受删除列的影响,因此读入第一行但随后未使用(如内联注释所标记),您可以改为简单地 寻找 第一行的末尾,然后在那之后开始 while 循环。

您可以使用此 -

代替您的循环
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);
}

是你帮我找到的,谢谢。这是解决方案:

 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");
}