简体   繁体   English

在C中进行文件处理:在文本文件的开头和结尾处删除空格

[英]File handling in C: Strip spaces at the beginning and end of text file

The following is a function that reads a file user.dat (attached after the code) and extracts a string and an int value delimited by ", " and "\\n" respectively. 以下是读取文件user.dat(附加在代码后)并提取分别由“,”和“ \\ n”分隔的字符串和int值的函数。

void getUsers()
{
     int i, t;
     char *token1, *u;
     FILE *fu = fopen("user.dat", "r");
     const char s[2] = ", ";
     if(fu != NULL)
     {
        char line1[20];
         while(fgets(line1, sizeof line1, fu) != NULL)
         {
             token1 = strtok(line1, s);
             for(i=0;i<2;i++)
             {
                 if(i==0)
                 {  
                     u = token1;
                     token1 = strtok(NULL,s);
                 } else {
                     t=atoi(token1);
                 }      
             }
             addOuterNode(u,t);
         }
         printOuterNode();
         fclose(fu);
     } else {
         perror("user.dat");
     }
}

The user.dat file is as follows: user.dat文件如下:

1000, 76
0095, 81
2910, 178
0001, 1
<EOF>

The program works fine if the above format is maintained. 如果保持上述格式,则程序可以正常运行。

However I run into problems (SIGSEGV generally as the *u and t values are sent to a function that inserts them into void * data elements in nodes of a linked list/nested linked list) when there are stray spaces or newlines in the file. 但是,当文件中有空格或换行符时,就会遇到问题(通常将SIGSEGV发送给将* u和t值插入到链接列表/嵌套链接列表的节点中的void *数据元素的函数中)。 Eg: 例如:

<newline>
1000, 76
 <space>
0095, 81
2910, 178
0001, 1
 <space><newline>
<newline>
<EOF>

Would you be able to help me to preprocess the user.dat textfile so that I can remove the unwanted whitespace characters? 您是否可以帮助我预处理user.dat文本文件,以便删除不需要的空白字符?

You can preprocess a file to exclude lines containing only whitespace characters. 您可以预处理文件以排除仅包含空格字符的行。 Eg in Perl this would be: perl -ne "print if !/^\\s*$/" input.txt > output.txt 例如,在Perl中,这将是:perl -ne“如果!/ ^ \\ s * $ /则打印” input.txt> output.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM