2015-03-13 27 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"); 
}