英文:
How to Open a text file utilising VSCode
问题
我遇到了一些我写的代码问题,我想打开一个txt文件,然后显示该文本文件中的人的姓名和成绩。我正在使用的代码如下:
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[10];
int marks[4];
};
int main()
{
struct student s[5];
int i = 0;
FILE *fp = fopen("Grades.txt", "r");
if (fp == NULL)
{
printf("Error Opening the input file\n");
return -1;
}
else
printf("File Opening successfully\n");
while (!feof(fp))
{
fscanf(fp, "%s", s[i].name);
for (int j = 0; j < 4; j++)
fscanf(fp, "%d", &s[i].marks[j]);
i++;
}
printf("The Grade details ....\n");
for (int i = 0; i < 5; i++)
{
printf("%s\n", s[i].name);
for (int j = 0; j < 4; j++)
printf("%d\n", s[i].marks[j]);
}
fclose(fp);
return 0;
}
无论我如何构造代码,都会出现错误文件'a.exe'已退出,代码为-1(0xffffffff)。
如果我做错了什么,请告诉我!
Peter
55
66
44
67
Lilly
100
90
43
89
John
34
56
78
65
Mary
45
56
78
90
Alex
30
45
65
54
英文:
Run into an issue with some code i wrote where i want to open a txt file and then display the name and grades of the people in said text file. The code i am using is as follows
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[10];
int marks[4];
};
int main()
{
struct student s[5];
int i=0;
FILE *fp=fopen("Grades.txt","r");
if(fp==NULL)
{
printf("Error Opening the input file\n");
return-1;
}
else
printf("File Opening successfully\n");
while(!feof(fp))
{
fscanf(fp,"%s", s[i].name);
for(int j=0; j<4; j++)
fscanf(fp,"%d", &s[i].marks[j]);
i++;
}
printf("The Grade details ....\n");
for(int i=0; i<5; i++)
{
printf("%s\n",s[i].name);
for( int j=0; j<4; j++)
printf("%d\n", s[i].marks[j]);
}
fclose(fp);
return 0;
}
No matter how i structure the code i get error file\a.exe' has exited with code -1 (0xffffffff).
If i have done something wrong please let me know!
Peter
55
66
44
67
Lilly
100
90
43
89
John
34
56
78
65
Mary
45
56
78
90
Alex
30
45
65
54
答案1
得分: 0
这个程序可能返回-1,是因为它无法打开Grades.txt
文件:
FILE* fp = fopen("Grades.txt","r");
if (fp == NULL)
{
printf("无法打开输入文件\n");
return -1;
}
如果你是在Visual Studio/Visual Studio Code中运行这个程序,很可能Grades.txt
文件不存在于可执行文件所在的同一文件夹中。
如果你真的想要硬编码文件路径,尝试指定一个绝对路径,而不是相对路径:fopen("C:\\Users\\Example\\Desktop\\Grades.txt","r");
"Grades.txt"
本身是一个相对路径,所以它需要存在于程序所在的相同文件夹/目录中。
英文:
The program is likely returning -1 because it cannot open Grades.txt
:
FILE* fp = fopen("Grades.txt","r");
if (fp == NULL)
{
printf("Error Opening the input file\n");
return -1;
}
If you are running this from inside Visual Studio/Visual Studio Code it is likely that Grades.txt
does not exist in the same folder as the executable file.
If you really want to hardcode the filepath, try specifying an absolute path rather than a relative one: fopen("C:\Users\Example\Desktop\Grades.txt","r");
"Grades.txt"
by itself is a relative path, so it needs to exist in the same folder/directory as the program.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论