删除字符" \ n"来自字符串与读取

时间:2015-03-13 15:24:30

标签: printf buffer stat opendir

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

我的代码:

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

由于

1 个答案:

答案 0 :(得分:0)

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