要读取当前目录中的txt文件,您可以使用以下代码示例来实现:
#includeint main() { FILE *file; char filename[100]; char line[100]; // 获取当前目录下txt文件的文件名 printf("Enter the name of the txt file in the current directory: "); scanf("%s", filename); // 打开文件 file = fopen(filename, "r"); // 检查文件是否成功打开 if (file == NULL) { printf("Error opening file.\n"); return 1; } // 读取文件内容并输出到控制台 while(fgets(line, sizeof(line), file)) { printf("%s", line); } // 关闭文件 fclose(file); return 0; }
在这个示例中,用户需要输入要读取的txt文件的文件名,然后程序会打开该文件并逐行读取文件内容并输出到控制台。最后,程序会关闭文件。请注意,这里假设txt文件在当前目录下。您也可以根据需要修改代码以适应不同的文件路径。