Tôi muốn chương trình C yêu cầu người dùng nhập tên của tệp mà họ muốn mở và in nội dung của tệp đó lên màn hình. Tôi đang làm việc từ hướng dẫn C và có đoạn mã sau cho đến nay. Nhưng khi tôi thực hiện nó, nó không thực sự cho phép tôi nhập tên tập tin. (Tôi nhận được 'nhấn bất kỳ nút nào để tiếp tục', tôi đang sử dụng mã hóa)Mở một tệp từ các đối số dòng lệnh trong C
Tôi đang làm gì sai ở đây?
#include <stdio.h>
int main (int argc, char *argv[])
{
printf("Enter the file name: \n");
//scanf
if (argc != 2) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf("usage: %s filename", argv[0]);
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen(argv[1], "r");
/* fopen returns 0, the NULL pointer, on failure */
if (file == 0)
{
printf("Could not open file\n");
}
else
{
int x;
/* Read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ((x = fgetc(file)) != EOF)
{
printf("%c", x);
}
fclose(file);
}
}
return 0;
}
+1. Đây là cách đặt câu hỏi về bài tập về nhà. "Tôi đã đi xa này và đã đánh một rào cản" thay vì "Viết chương trình này cho tôi". –