k12*_*234 5 c stdin file c-strings
自从我用 C 编程以来已经有很多年了,所以我一直在努力做一个简单的“从标准输入获取文件名和路径,读取文件,将文件打印到标准输出”任务,我知道这不应该那么难但是你。这是我的代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void) {
int c;
FILE *file;
//scanf("%s", filename);
char *filename;
filename = (char *)malloc(200 * sizeof(char));
read(STDIN_FILENO, filename, 200);
printf("%s", filename);
file = fopen(filename, "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
} else {
printf("File not found.");
}
printf("\n");
return(0);
}
Run Code Online (Sandbox Code Playgroud)
我的代码继续简单地打印出来File not found.,当我知道我的文件路径并且一切都是正确的(不仅因为我真的把它从我的文件夹中删除并通过 Mac OSX El Capitan 将它传递到终端 - 多么可爱的功能,但是也)因为我有这个程序的不同版本,它使用scanf它找到了文件并完全正确地读取它,(正如你所看到的,我在我的代码中注释掉了它)。
我正在编写另一个程序,它只是使用这个程序,我摆脱了它,scanf因为我认为它对该程序中的其他事物产生了负面影响,所以我希望能够使用read()
如果有人对我如何解决这个问题或为什么这不起作用有任何建议,那将不胜感激,因为我已经在这里工作了几个小时,并且非常想继续我需要的实际程序代码!
感谢一堆
您必须删除'\n'正在读取并存储到filename缓冲区中的换行符。
其中之一就是包含string.h并阅读文件名后
char *newline = strchr(filename, '\n');
if (newline != NULL)
*newline = '\0';
Run Code Online (Sandbox Code Playgroud)
此外,使用fgets()而不是read()因为这样程序更易于移植。更重要的是,read()不会添加null终止符,这对于将缓冲区用作字符串非常重要 -例如将其传递给fopen()- 正确。如果你想使用 read 尝试这样的事情
ssize_t length;
char filename[200];
length = read(STDIN_FILENO, filename, sizeof(filename) - 1);
if (length <= 0)
return -1; // No input or input error
if (filename[length] == '\n')
filename[--length] = '\0';
else
filename[length] = '\0';
Run Code Online (Sandbox Code Playgroud)
但否则,试试这个更简单的
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *file;
char filename[200];
char *newline;
if (fgets(filename, sizeof(filename), stdin) == NULL)
return -1; // Input error / EOF
newline = strchr(filename, '\n');
if (newline) // ? is a newline present?
*newline = '\0';
printf("**%s**\n", filename); // ** will help checking for
// the presence of white spaces.
file = fopen(filename, "r");
if (file) {
int chr;
while ((chr = fgetc(file)) != EOF)
fputc(chr, stdout);
fclose(file);
} else {
printf("File not found.");
}
printf("\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)