| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2931 人关注过本帖
标题:高手请教:链表读入读出文件出现乱码
只看楼主 加入收藏
cryingcamel
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2010-9-1
收藏
得分:0 
最后是(fwrite((p+i),LEN,1,fp)!=1)中的LEN-4,之后就可以了。其中4代表的是struct中结构体指针所代表的长度,这个好像不能存入文件……
现在读入读出数据都可以了,没问题,但是就是查看txt文件的时候有很多屯屯屯屯屯屯屯屯屯屯屯屯……乱七八糟的,老师说还是有问题,不正常。
到底是咋存到text文件的呢?那些屯屯正常吗?

i love c
2010-09-02 12:49
唐小虎
Rank: 3Rank: 3
等 级:论坛游侠
威 望:1
帖 子:46
专家分:119
注 册:2010-6-25
收藏
得分:4 
顶一下
2010-09-02 13:04
erikyo
Rank: 9Rank: 9Rank: 9
等 级:蜘蛛侠
威 望:2
帖 子:270
专家分:1154
注 册:2010-6-10
收藏
得分:4 
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

struct shares  
{
    char name[20];
    char num[20];
    int  date;
    long price;
    char sort[15];
    char company[20];
    struct shares * next;
};

#define LEN sizeof(struct shares)
#define NUM 2

int n=0;

struct shares * input()// 录入函数//
{
   
    struct shares * head=0;
    struct shares *p1,*p2;
    while(n<NUM)
    {
        p1=(struct shares *)malloc(LEN);
        scanf("%s %s %d %ld %s %s",p1->name,p1->num,&p1->date,&p1->price,p1->sort,p1->company);
        n=n+1;
        if(n==1)
            head=p1;
        else
            p2->next=p1;

        p2=p1;   
    }
    p2->next=NULL;

    return(head);
}

void save(struct shares * head)   //保存记录//
{
    FILE * fp;
    struct shares *p = head;
    int i;
    if((fp=fopen("F:\\data.txt","wb"))==NULL)
    {
        printf("cannot open the file\n");
        return;
    }
    while(p)                    //循环的条件换一下。(p+i)->next!=0,那第三心爱那个是无法输出的,因为当i=2时,条件不成了了,不能写入文件
    {
        if(fwrite(p,LEN,1,fp)!=1)
            printf("file write error\n");
        
        p = p->next;
    }
    fclose(fp);
}


void read(struct shares *head)                //读取数据//
{
    int i;
    struct shares *pp = head;
    FILE *fp;
    fp=fopen("F:\\data.txt","rb");
    for(i=0;pp!=NULL;i++)                    //和在save中的错误一样,改变循环条件
    {
        fread(pp,LEN,1,fp);                        
        printf("\n%s %s %d %ld %s %s\n",pp->name,pp->num,pp->date,pp->price,pp->sort,pp->company);
        pp = pp->next;                                    
    }
}


int main()
{
    struct shares * head;
    head=input();
    save(head);
    read(head);
   
    return 0;
}
还有写文件如果不是二进制文件的话,最好不要用fwrite和fread改用fprintf和fscanf
2010-09-02 18:23
cryingcamel
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2010-9-1
收藏
得分:0 
对头,用fscanf和fprint可以了
thanks ls

i love c
2010-09-02 19:22
快速回复:高手请教:链表读入读出文件出现乱码
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014505 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved