我知道如何硬编程序来接收文件但是当我尝试使用scanf类似的策略时,没有任何反应。我的意思是我有一个错误检查,看看它是否存在以及它是否具有正确的格式,但每次我输入文件名时都会在scanf下面打印printf语句。这是为什么?我还发现我打开文件但是while语句是无限的。哪个没有意义。我尝试了下面显示的另一个解决方案但结果相同。
void parseFile(struct student_record_node** head)
{
FILE*input;
const int argCount = 4;
char filename[100]="";
const char rowformat[] = "%20s %20s %d %d";
struct student_record record;
struct student_record_node* node = NULL;
printf("\n Please Enter the FULL Path of the .txt file you like to load. \n");
scanf("%s",filename);
input = fopen(filename, "r");
printf("I am here");
if(input == NULL)
{
printf("Error: Unable to open file.\n");
exit(EXIT_FAILURE);
}
while(!feof(input))
{
/* creating blank node to fill repeatedly until end of document*/
memset(&record, 0, sizeof(struct student_record));
if(fscanf(input, rowformat, record.first_name_,record.last_name_,&record.student_id_,&record.student_age_) != argCount)
{
continue;
}
/* set node into the doubly linked list */
node = student_record_allocate();
/* copies values from the blank node reading from document into node in my linked list */
strcpy(node->record_->first_name_, record.first_name_);
strcpy(node->record_->last_name_, record.last_name_);
node->record_->student_id_ = record.student_id_;
node->record_->student_age_ = record.student_age_;
/* check if node right after absolute head is empty if so fills it */
if(*head == NULL)
{
*head = node;
}
else
{
printf(" stuck in loop\n");
/* if current isn't null start linking the node in a list */
appendNode(head,node);
}
}
fclose(input);
printf(" end of parsefile");
}
当我进入parsefile()函数并输入正确格式的NEW.txt并且与程序本身位于同一文件夹内。我知道当我输入一个不存在的.txt文件或者它是空的时,我的检查工作正常。它会像它应该被捕获一样。
预期的行为是程序应该从new.txt加载此列表并将其加载到双向链表中。然后返回到提供用户选项的菜单。然后可以操纵所列出的双重链接,例如添加学生操纵数据,删除,保存和打印当前名单。我从这个程序使用gdb时遇到了麻烦,因为我从parsefile收到了new.txt。
New.txt内容示例。 (它只是名字,姓氏,身份证,年龄)
Belinda Homes 345 50
Scott Crown 456 18
解决方案失败:使用fgetc而不是feof
int c = fgetc(input);
while(c != EOF)
{
printf("\n in loop \n");
/* creating blank node to fill repeatedly until end of document*/
memset(&record, 0, sizeof(struct student_record));
if(fscanf(input, rowformat, record.first_name_,record.last_name_,&record.student_id_,&record.student_age_) != argCount)
{
continue;
}
/* set node into the doubly linked list */
node = student_record_allocate();
/* copies values from the blank node reading from document into node in my linked list */
strcpy(node->record_->first_name_, record.first_name_);
strcpy(node->record_->last_name_, record.last_name_);
node->record_->student_id_ = record.student_id_;
node->record_->student_age_ = record.student_age_;
/* check if node right after absolute head is empty if so fills it */
if(*head == NULL)
{
*head = node;
}
else
{
printf(" stuck in loop\n");
/* if current isn't null start linking the node in a list */
appendNode(head,node);
}
c = fgetc(input);
}
答案 0 :(得分:1)
这是从文件读取和打印输出的最简单方法。我假设你想打印文件或用它做一些事情。
int c;
FILE *file;
file = fopen("test.txt", "r");
if (file) {
while ((c = getc(file)) != EOF){
putchar(c);
}
fclose(file);
}