2015-03-13 25 views
0

我必须做一个项目,但我遇到了问题。 我从阅读中收到一个字符串,但是当我看到缓冲区中有什么数据时,它会在文件末尾显示“\ n”。但是我不需要它来处理函数中的一个参数。从字符串中删除字符“ 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 
} 

感谢

回答

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