如何把文本文件从到数组 [英] How to put text from file into array

查看:153
本文介绍了如何把文本文件从到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从文件中读取文本(几句话的文本),然后记下所有的字符。要做到这一点,我需要使用数组。我写这篇code,但它给了我什么。

 的#include<&stdio.h中GT;诠释主要(无效){
  INT I;
  FILE *在=的fopen(test.txt的,R);  如果(在){
    焦炭MAS [50];
    为size_t N = 0;
    INT CH;
    而((CH = GETC(中))!= EOF){
      MAS [N +] =(char)的CH;
    }
    fclose函数(在);
  }  对于(i = 0; I< 50;我++){
    的printf(%C,MAS [I]);
    的printf(\\ n);
  }
  返回0;
}


解决方案

  //低电平输入输出命令的方法#包括LT&;&fcntl.h GT;诠释的main()
{
    INT X,I,N,V = 1;
    个char [256],STR;    对于(i = 1; I< = 255;我++)
        S [I] ='0';
    X =打开(out.txt,O_RDONLY);    如果(X == - 1)
    {
        的printf(无效的文件路径);
        返回0;
    }    而(N!= 0)
    {
        N =读(X,&放大器; STR,1);
        S [(int)的海峡] ='1';
        V = 0;
    }
    关闭(X);    对于(i = 1; I< = 255;我++)
        如果(S [I] =='1')
            的printf(%C(字符)我);    如果(v)的
        的printf(空白文件!);
    关闭(X);    返回0;
}

I need to read text from a file (text of few sentences) and then write down all unique characters. To do that I need to use an array. I wrote this code but it gives me nothing.

#include <stdio.h>

int main(void) {
  int i;
  FILE *in = fopen("test.txt", "r");

  if (in) {
    char mas[50];
    size_t n = 0;
    int ch;
    while ((ch = getc(in)) != EOF) {
      mas[n++] = (char)ch;
    }
    fclose(in);
  }

  for (i = 0; i < 50; i++) {
    printf("%c", mas[i]);
    printf("\n");
  }
  return 0;
}

解决方案

//low level input output commands method

#include <fcntl.h>

int main()
{
    int x,i,n,v=1;
    char s[256],str;

    for (i=1;i<=255;i++)
        s[i]='0';
    x=open("out.txt",O_RDONLY);

    if (x==-1)
    {
        printf("Invalid file path");
        return 0;
    }

    while (n!=0)
    {
        n=read(x,&str,1);
        s[(int)str]='1';
        v=0;
    }
    close(x);

    for (i=1;i<=255;i++)
        if (s[i]=='1')
            printf("%c",(char)i);

    if (v)
        printf("Blank file!");
    close(x);

    return 0;
}

这篇关于如何把文本文件从到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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