从文件中读取和存储阵列 [英] Reading from a file and storing in array

查看:87
本文介绍了从文件中读取和存储阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了下面的程序按行从文件中读取行并将其存储在词数组中为止。输出应该是从数组两个随机字。但令人惊讶的话数组只包含的最后一个字反复读。在什么地方出了错任何帮助吗?

  INT的main(){
 INT I = 0;
 烧焦line_buffer [BUFSIZ];
 字符*字[20];
 FILE *计划生育=的fopen(input.txt的,R);
  而(与fgets(line_buffer,sizeof的(line_buffer),FP)){
  //的printf(%S,line_buffer);
  字[I] = line_buffer;
  I = I + 1;
 }
 的printf(%D,我);
 INT J =兰特()%8;
    INT K =(J + 1)%8;
 的printf(%s%S,字[J],字[K]);
 FCLOSE(FP);
 返回0;
}

input.txt的

 线虫知识
空瓶子
虽然
幽闭恐惧症
变态
承认
不可能的事
永不放弃


解决方案

您读取数据的每一行到相同的缓冲区,这样最后一行将覆盖所有previous线。你将不得不为通过某种手段或其他每一行分配空间 - 以无论是动态内存分配的malloc()(或可能的strdup( )),或使用一个固定大小的数组(这限制了你的程序能够安全地处理数据)的数量。您还需要处理数据的新行读取。

您得到一些信贷使用与fgets()而不是使用获得();这是一个100%正确的决定。


 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&time.h中GT;枚举{MAXLINES = 30};INT主要(无效)
{
    INT I = 0;
    焦线[MAXLINES] [BUFSIZ];
    FILE *计划生育=的fopen(input.txt的,R);    如果(FP == 0)
    {
        fprintf中(标准错误,未能打开input.txt的\\ n);
        出口(1);
    }
    而(ⅰ&所述; MAXLINES&放大器;&放大器;与fgets(行[I],sizeof的(行[0]),FP))
    {
        线[I] [strlen的(行[I]) - 1] ='\\ 0';
        I = I + 1;
    }
    FCLOSE(FP);
    的printf(%d个\\ N,I);
    函数srand(时间(0));
    INT J =兰特()%I;
    INT K =(J + 1)%I;
    的printf(%s%S \\ n,行[J],行[K]);
    返回0;
}

这将检查该文件已成功打开,只要读完成关闭文件,并确保它不被读取更多的行比阵列可以容纳触发栈溢出。它浪费由过度分配的空间,以便在每行可能是很长的一个很大的空间(虽然线通常相当短)。如果一个线比BUFSIZ较长,它将会在行被读入一对相邻的条目。它不假设有8行中的数据文件。困住在每行(除非线被分割,在这种情况下,它在第一两线的分割前跳越的最后一个字符)的末尾的换行符。它的种子随机数生成当前时间。这似乎很奇怪,你只曾经想从文件中相邻行。

I've written the following program to read line by line from a file and store it in the words array. The output should be two random words from the array. But surprisingly the words array contains only the last word read repeatedly. Any help on what went wrong?

int main(){
 int i = 0;
 char line_buffer[BUFSIZ];
 char* words[20];
 FILE *fp = fopen("input.txt", "r");
  while (fgets(line_buffer, sizeof(line_buffer), fp)) {
  //printf("%s", line_buffer); 
  words[i] = line_buffer;
  i = i + 1;
 } 
 printf("%d", i);
 int j = rand()%8;
    int k = (j+1)%8;
 printf("%s %s", words[j], words[k]); 
 fclose(fp);
 return 0;
}

input.txt

nematode knowledge
empty bottle
nevertheless
claustrophobia
metamorphosis
acknowledgement
impossibility
never gave up

解决方案

You read each line of data into the same buffer, so the last line overwrites all previous lines. You're going to have to allocate space for each line by some means or other - either dynamic memory allocation with malloc() (or possibly strdup()), or using a fixed size array (which limits the amount of data your program can handle safely). You'll also need to deal with newlines in the data read.

You get some credit for using fgets() and not using gets(); that is a 100% correct decision.


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

enum { MAXLINES = 30 };

int main(void)
{
    int i = 0;
    char lines[MAXLINES][BUFSIZ];
    FILE *fp = fopen("input.txt", "r");

    if (fp == 0)
    {
        fprintf(stderr, "failed to open input.txt\n");
        exit(1);
    }
    while (i < MAXLINES && fgets(lines[i], sizeof(lines[0]), fp))
    {
        lines[i][strlen(lines[i])-1] = '\0';
        i = i + 1;
    }
    fclose(fp);
    printf("%d\n", i);
    srand(time(0));
    int j = rand() % i;
    int k = (j+1) % i;
    printf("%s %s\n", lines[j], lines[k]); 
    return 0;
}

This checks that the file was opened successfully, closes the file as soon as the reading is complete, and ensures that it does not trigger a stack overflow by reading more lines than the array can hold. It wastes a lot of space by over-allocating space so each line could be very long (though the lines are typically quite short). If a line is longer than BUFSIZ, it will be read into a couple of adjacent entries in lines. It does not assume that there are 8 lines in the data file. It zaps the newline at the end of each line (unless a line is split, in which case it zaps the last character before the split on the first of the two lines). It seeds the random number generator with the current time. It seems odd that you only ever want adjacent lines from the file.

这篇关于从文件中读取和存储阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆