简体   繁体   English

从C中的文本文件读取,在模式中找到换行符和空格

[英]Reading from textfile in C, finding newline and blank space in pattern

I am reading from a textfile and there is a pattern. 我正在从文本文件中读取内容,并且有一个模式。 I am currently reading the file with help of tokens. 我目前正在借助令牌读取文件。 There are many lines and the pattern breaks if there are any spaces or row breaks after the pattern is finished. 有很多行,并且模式完成后,如果有空格或行中断,则模式中断。 This is what I have tried so far: 到目前为止,这是我尝试过的:

char newLine[10];
strcpy(newLine, "\n");
int stringValue;
....
*readfromfile*
{
    ...
    stringValue = strcmp(token, newLine);
    if(stringValue == 0)
    {
        ...

So if there is a new line or blank space after the line I want the if statement to go through. 因此,如果在该行之后有新行或空白,我希望if语句通过。 Does anyone know how to solve this? 有谁知道如何解决这个问题? Is it that token doesn't aquire the character, " " and "\\n". 是令牌不获取字符“”和“ \\ n”。 If so, what can I do to solve it? 如果是这样,我该怎么办?

Just trim(newline) before calling strcmp() . 只需在调用strcmp()之前trim(newline) strcmp() trim() will remove any blanks at the beginning or the end of the string. trim()将删除字符串开头或结尾的所有空格。

You can found an example in C in this question . 您可以在C 找到有关此问题的示例。

There's another way: if there's blanks at the end of newLine that you don't want to compare by using strcmp() , use strncmp() instead (with the length of token ). 还有另一种方法:如果您不想通过使用strcmp()比较newLine末尾的newLine ,请改用strncmp() (带有token的长度)。

As per your comment you are reading buffer first and then want to remove characters then do as below example, (with assumption your buffer size is of 1024) 根据您的评论,您先读取缓冲区,然后要删除字符,然后按以下示例操作(假设您的缓冲区大小为1024)

int RemoveTokens(char *string)
{
   char  buf[1024] = {0};
   int   i         = 0;
   int   j         = 0;

   strncpy(buf, string, 1024);
   memset(string, 0x00, 1024);
   for (i=0; i<1024; i++)
   {
      if (' ' != buf[i] && '\n' != buf[i])
      {
         string[j] = buf[i];
         j++;
      }
   }
}

Hope it will helps you to do it easily. 希望它可以帮助您轻松实现。 :D :D

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

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