C语言怎样将.txt文件中的数据写入到结构体中去

Python011

C语言怎样将.txt文件中的数据写入到结构体中去,第1张

txt文件中的数据写入到结构体中去的源代码如下:

#include<stdio.h>

#include <string.h>

//可以退出的头文件

#include <stdlib.h>

//结构体的长度

#define DATALEN 15

//函数声明

//定义结构数组

struct wordUnit{

int id//id

char word[10]//词语

char depId[10]//依存词语的id

char pos[10]//词性

char depRel[10]//依存目标的关系

}

int main(){

FILE *data//要读取的文件指针

int i=0//结构题数组移动

struct wordUnit words[DATALEN]

if((data=fopen("data3.txt","r"))==NULL){

printf("Can not open file\n")

return 0

}

while(!feof(data)){

//原txt文档的数据之间是以空格隔开的

}

fclose(data)

for(int j=0j<ij++){

}

return 0

}

扩展资料

1、使用关键字struct,它表示接下来是一个结构体。

2、后面是一个可选的标志(book),它是用来引用该结构体的快速标记。

一般有两种方法.

struct A

{

    int a

    float f

    char s[10]

}m

为例:

一种是写文本文件

以"w"打开

fprintf(fp, "%d %f %s\n", m.a,m.f, m.s)

另一种是写二进制文件.

以"wb"打开

fwrite(&m, sizeof(m), 1, fp)

C语言把一个结构体数组写入文件分三步:

1、以二进制写方式(wb)打开文件

2、调用写入函数fwrite()将结构体数据写入文件

3、关闭文件指针

相应的,读文件也要与之匹配:

1、以二进制读方式(rb)打开文件

2、调用读文件函数fread()读取文件中的数据到结构体变量

3、关闭文件指针

参考代码如下:

#include<stdio.h>

struct stu {

char name[30]

int age

double score

}

int read_file()

int write_file()

int main()

{

if ( write_file() < 0 ) //将结构体数据写入文件

return -1

read_file() //读文件,并显示数据

return 0

}

int write_file()

{

FILE *fp=NULL

struct stu student={"zhang san", 18, 99.5}

fp=fopen( "stu.dat", "wb" ) //b表示以二进制方式打开文件

if( fp == NULL ) //打开文件失败,返回错误信息

{

printf("open file for write error\n")

return -1

}

fwrite( &student, sizeof(struct stu), 1, fp ) //向文件中写入数据

fclose(fp)//关闭文件

return 0

}

int read_file()

{

FILE *fp=NULL

struct stu student

fp=fopen( "stu.dat", "rb" )//b表示以二进制方式打开文件

if( fp == NULL ) //打开文件失败,返回错误信息

{

printf("open file for read error\n")

return -1

}

fread( &student, sizeof(struct stu), 1, fp ) //读文件中数据到结构体

printf("name=\"%s\" age=%d score=%.2lf\n", student.name, student.age, student.score ) //显示结构体中的数据

fclose(fp)//关闭文件

return 0

}

fwrite(const void*buffer,size_t size,size_t count,FILE*stream)

(1)buffer:指向结构体的指针(数据首地址)   

(2)size:一个数据项的大小(一般为结构体大小)

(3)count: 要写入的数据项的个数,即size的个数   

(4)stream:文件指针。