fscanf,structs和使用struct c编程

时间:2014-02-04 04:23:32

标签: c struct

/*Project 1
Student records

1. Read the file with the records
2. store them
3. sort them
4. output them

ex. input and output (SORTED by student ID

2040003 AAAA BBBBBBBBB ComputerScience 3.45
2040002 AAA CCC ElectricalEngineering 3.01
2040005 AAAAAAAAAAAAAAAAA BBB ComputerScience 3.60

2040002,AAA,CCC,ElectricalEngineering,3.01
2040003,AAAA,BBBBBBBBB,ComputerScience,3.45
2040005,AAAAAAAAAAAAAAAAA,BBB,ComputerScience,3.60

char* name = malloc(256*sizeof(char));
*/ 

int main()
{
typedef struct StudentRecords
{
    int StudentID; //must be of size 7 between 1000000 and 9999999
    char *Firstname; //= MALLOC(256*sizeof(char)); // must be any length and allocate memory dynamically.
    char *Lastname; //= MALLOC(256*sizeof(char));
    char *Department; //= MALLOC(256*sizeof(char));
    float GPA; // must be between 0 and 4
} STUDENTRECORDS; 

/*
    First job is read the file
*/

//set variables
int i=0;
char filecontent, file_name[100];
FILE *fp;
STUDENTRECORDS StudentRecords[300];
STUDENTRECORDS a[300];
int size =0;


printf("Enter directory of file\n"); // instructs user to enter directory of file
gets(file_name); //prompt use

fp = fopen(file_name,"r"); //opens the file "r" is read mode for fopen()

// here is a check to see if fp is empty and throw an error if so
if (fp == NULL)
{
        perror("Could not open file\n");
        exit(EXIT_FAILURE);
}

printf("The contents of %s file are :\n", file_name); // just prints the file name (file_name) you are prompted for

// here is where the printing of contents actually occurs
while ((filecontent = fgetc(fp)) != EOF) // I think EOF is end of feed here, not 100%
{
    printf("%c",filecontent);
}

//I thought this line was to figure out how many lines are in the text, but it isnt working.
while (!feof(fp)) 
{
        read(StudentRecords, i, fp);
        i++;
}

//because the while statement isnt working, Ive elected to setting size to 3 in order to continue coding.
size = i = 3;
printf("Size = %d\n", size);

//I thought this essentially put the files contents into 
for (i = 0; i < size; ++i)
    fscanf(fp, "%d %s %s %s %f\n", &StudentRecords[i].StudentID, &StudentRecords[i].Firstname, &StudentRecords[i].Lastname, &StudentRecords[i].Department, &StudentRecords[i].GPA);

for (i = 0; i < size; ++i)
    printf("%s", StudentRecords[i]);
    //printf("%d %s %s %s %f/n", &StudentRecords[i].StudentID, &StudentRecords[i].Firstname, &StudentRecords[i].Lastname, &StudentRecords[i].Department, &StudentRecords[i].GPA);

for (i = 0; i < size; ++i)
    fscanf(fp, "%d %s %s %s %f\n", &a[i].StudentID, &a[i].Firstname, &a[i].Lastname, &a[i].Department, &a[i].GPA);

for (i = 0; i < size; ++i)
    printf("%s", a[i]);
    //printf("%d %s %s %s %f/n", &a[i].StudentID, &a[i].Firstname, &a[i].Lastname, &a[i].Department, &a[i].GPA);


// fclose() must follow an fopen()
fclose(fp);

//printf("%g", &StudentRecords);


// return code
return 0;

}

如何将信息添加到结构中并打印或使用它?这是什么 我到目前为止。我尝试了很多不同的东西但无济于事。我认为问题在于我初始化我的结构以供使用。我做不到。我已经尝试过寻找解决方案,但每个解决方案都有所不同,并且解释不多。

感谢您的任何建议。

2 个答案:

答案 0 :(得分:2)

请查找用于从文件中读取内容并将其存储在结构中的示例代码,对于此示例,只需要输入5个学生数据(您可以根据需要进行更改)以及您要对哪个条件进行排序?所以我给你排序。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_ENTRY 5
typedef struct StudentRecords
{
    int StudentID; //must be of size 7 between 1000000 and 9999999
    char *Firstname; //= MALLOC(256*sizeof(char)); // must be any length and allocate memory dynamically.
    char *Lastname; //= MALLOC(256*sizeof(char));
    char *Department; //= MALLOC(256*sizeof(char));
    float GPA; // must be between 0 and 4
} STUDENTRECORDS; 

int main()
{
    /*
        First job is read the file
    */

    //set variables
    int i=0;
    char filecontent, file_name[100];
    FILE *fp;

    STUDENTRECORDS StudentRecords[MAX_ENTRY];

    for(i=0;i<MAX_ENTRY;i++)
    {
        StudentRecords[i].Firstname = malloc(sizeof(char)*256);
        StudentRecords[i].Lastname = malloc(sizeof(char)*256);
        StudentRecords[i].Department = malloc(sizeof(char)*256);        
    }

    printf("Enter directory of file\n"); // instructs user to enter directory of file
    gets(file_name); //prompt use

    fp = fopen(file_name,"r"); //opens the file "r" is read mode for fopen()

    // here is a check to see if fp is empty and throw an error if so
    if (fp == NULL)
    {
        perror("Could not open file\n");
        //exit(EXIT_FAILURE);
    }

    i=0;
    while(EOF!=fscanf(fp, "%d %s %s %s %f\n", &StudentRecords[i].StudentID, StudentRecords[i].Firstname, StudentRecords[i].Lastname, StudentRecords[i].Department, &StudentRecords[i].GPA))
    {
        printf("%d %s %s %s %f\n", StudentRecords[i].StudentID, StudentRecords[i].Firstname, StudentRecords[i].Lastname, StudentRecords[i].Department, StudentRecords[i].GPA);
        i++;
    }


    // fclose() must follow an fopen()
    fclose(fp);

    return 0;
}

注意:永远不要忘记释放malloc在使用后分配的字符串。

答案 1 :(得分:0)

一些评论和一些建议:

你的讲师是不是说要使用链接列表?如果是这样的话......你真的应该这样做,否则你会因为不符合规范而失去分数。

EOF是文件结尾&#39;。 feof()告诉你传递给它的流指针是否已经命中了EOF。

打印内容的while循环效率低下。而不是每一个阅读。单。字符。在里面。文件。,你应该读取整个文件(或至少,大块,不要假设无限的内存),fclose()流然后操作读入文件。

此外,这种练习非常适合固定大小的记录

省略错误处理,变量声明,结构和 使用一些伪代码:

stat("/path/to/file", &statbuf)
inputfd = fopen("/path/to/file", r);
/* assuming that we only have a small file... */
contents = calloc(statbuf.st_size * sizeof(char));
/* read it all in, in one big chunk */
fread(contents, statbuf.st_size, 1, inputfd);
fclose(inputfd);

/* Now you can operate on it however you like */
bytesleft = statbuf.st_size;
/*
 * this might need to go at the top of your block, depends on if you
 * have enabled C99
 */
char eachline[MAXLINELENGTH];
int n = 0;
while (bytesleft > 0) {
    add_new_list_element(mylist);
    bzero(eachline, MAXLINELENTH);
    memccpy(&eachline, contents[n], '\n', MAXLINELENGTH);
    bytesleft -= sizeof(eachline);
    nread = sscanf(start, "USE YOUR FORMAT STRING HERE", [variable list]);
    if (nread < 0)
        /* handle EOF, remember to make use of errno */
}

call_my_sort_function(mylist);
for (; thiselement != NULL; thiselement = thiselement->next)
    print_salient_field_values(thiselement);