| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 499 人关注过本帖
标题:麻烦纠个错谢谢
只看楼主 加入收藏
Timber
Rank: 1
等 级:新手上路
帖 子:42
专家分:0
注 册:2010-1-31
结帖率:71.43%
收藏
 问题点数:0 回复次数:0 
麻烦纠个错谢谢
Write a program which reads lines from a text file into a dynamically allocated array.
Program may use a static limit for line length.
Hint: First open the file then read (and discard) all lines to count
how many lines there are in the file. Then reopen the file to really read the data.

程序代码:
#include <stdio.h>
#include <stdlib.h>
#include  <conio.h>
#include <string.h>

#define MY_FILENAME "data.txt"
#define FILESIZE 50
#define LINE_LENGTH 255

int main()
{
    FILE *fp;
    int h=0;
    int i;
    char c;
    char *data[LINE_LENGTH+1];
    char cur[LINE_LENGTH+1];
    char filename[FILESIZE]="data.txt",fileinput[FILESIZE],*fileptr;/*share the same file with no.30,so use the address form..*/
    printf("Please enter a filename!\n");
    scanf("%s",fileinput);
    fileptr=strstr(filename,fileinput);
    if (fileptr)
    {
        if ((fp=fopen("data.txt","r"))==NULL)
        {
            printf("Cannot open file strike any key exit!");
            getch();
            exit(1);
        }
        else
            while (!feof(fp))
            {
                if (fgetc(fp)=='\n')
                    h++;
                else;
                {
                    c=getc(fp);
                    if (c==EOF)
                    {
                        h++;
                        break;
                    }
                }
            }
        printf("%d\n",h);
        fclose(fp);
    }
    if ((fp=fopen(MY_FILENAME, "r")) == NULL)
    {
        printf("freopen error!\n");
        exit(1);
    }
    else
    {
        printf("read successfully\n");
        fseek(fp,0,SEEK_SET);
        for (i=0;i<h ;i++ )
        {
            if (fgets(cur,LINE_LENGTH,fp))
            {
                data[i]=(char *)malloc(strlen(cur)*sizeof(char));
                if (data[i]==NULL)
                {
                    printf("malloc error!\n");
                    exit(1);
                }
                strcpy(data[i],cur);
                printf("%s",data[i]);
                free(data[i]);
            }

        }
    }
    fclose(fp);

    return 0;
}
data.txt的内容就是题干
运行结果在下面图片里
只显示了两行
然后就死机
调试没有问题

图片附件: 游客没有浏览图片的权限,请 登录注册

图片附件: 游客没有浏览图片的权限,请 登录注册


[ 本帖最后由 Timber 于 2010-5-16 18:01 编辑 ]
搜索更多相关主题的帖子: 麻烦 
2010-05-16 17:53
快速回复:麻烦纠个错谢谢
数据加载中...
 
   



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

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