【问题标题】:Delete character "\n" from string with read用 read 从字符串中删除字符“\n”
【发布时间】:2015-03-13 15:24:30
【问题描述】:

我要做一个项目,但我遇到了问题。 我从读取中收到一个字符串,但是当我看到缓冲区中有哪些数据时,它会在文件末尾显示一个“\n”。但是我不需要它来使用 after 来处理我的函数中的参数。

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>

int main() 
{

char buf[100];
read(1, buf, sizeof(buf));
printf("%s", &buf);
// If I write: "/tmp/", printf shows: "/tmp/\n"
DIR* drp = opendir(buf);
// Logically: no such file or directory
}

谢谢

【问题讨论】:

    标签: printf buffer stat opendir


    【解决方案1】:

    stdin 读取字符串的问题。 read 函数会一直等待,直到您输入换行符或其他 EOF 键。但它在结果中包含了最后一个符号。

    1) 我认为你最好使用scanf

    scanf("%s", buf);
    

    2) 或者你需要自己处理最后一个符号。

    char buf[100];
    char res[100];
    int n = read(1, buf, sizeof(buf));
    if(n > 0) {
       memcpy(res, buf, n - 1);
    } else {
       printf("Error while reading\n");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 2012-09-23
      • 1970-01-01
      相关资源
      最近更新 更多