【发布时间】:2021-04-01 03:02:36
【问题描述】:
我的问题是是否可以忽略稍后使用fscanf() 存储在结构中的 txt 文件的特定部分。
出于示例的目的,让我说我有一个由以下文本组成的 txt 文件:
Title: C Programming Language
Author: Dennis Ritchie
Publication year: 1978
...
我想将数据存储在这样的结构中,忽略Title:、Author:、Publication year: 等字样:
struct book {
char title[MAX];
char author[MAX];
int pubblication_year;
...
};
这是我为了存储数据而实现的代码:
fscanf(fp, "%[^\n]%*c\n", newOne->books.title); //titolo
fscanf(fp, "%[^\n]%*c\n", newOne->books.author); //autore
fscanf(fp, "%d\n", &newOne->books.pubblication_year); //anno pubblicazione
...
这里是一个简单的例子:
#include <stdio.h>
#include <stdlib.h>
#define MAX 30
struct book {
char title[MAX];
char author[MAX];
};
struct booklist {
struct book books;
struct booklist *next;
};
int main() {
struct booklist *head = NULL, *newOne, *temp; //temp made in order to clear the heap once the program is termined
FILE *fp;
fp = fopen("FileName.txt", "r");
if(fp == NULL) {
printf("Something wrong happened, the program will close!\n");
system("pause");
exit(1);
} else {
newOne = (struct booklist *)malloc(sizeof(struct booklist));
if(newOne == NULL) {
printf("Error, not enough space to store the new book, the program will close!\n");
system("Pause");
exit(1);
}
fscanf(fp, "%[^\n]%*c\n", newOne->books.title); //ADDING THE TITLE TO THE NODE
fscanf(fp, "%[^\n]%*c\n", newOne->books.author); //SAME FOR THE AUTHOR
//adding the new one node created to the head of the list
newOne->next = head;
head = newOne;
}
while (newOne != NULL) { //cleaning the heap once the program is termined
temp = newOne;
newOne = newOne -> next;
free(temp);
}
fclose(fp);
return 0;
}
有没有可能?
【问题讨论】:
-
要忽略冒号前的单词吗?
-
我想忽略“Title:/Author:”等字样
-
冒号前面肯定是对的?
-
您的问题与结构和文件无关。如果您只想从键盘读取到一个简单的数组,解决方案是相同的。
-
你明白我想做什么了吗?顺便说一句,英语也不是我的第一语言,所以问题可能是我无法解释自己。