【C语言】从文件每次读入一行字符串,并把这些字符串添加到字符串数组中

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

问题描述

从文件每次读入一行字符串,并把这些字符串添加到字符串数组中

测试文件rwq.txt

hello
jjjjj
ddddd
44444l
hello
hello
jjjjj
ddddd
jjjjj
ddddd

实现

  • 读入一行之后需要处理末尾的\n,改成\0
  • 使用char* 数组来表示二维char数组
#include 
#include
int main()
{
    FILE * pFile;
    char mystring [100];
    char* res[999];    //store final result

    int p=0;    //pointer of res[]
    pFile = fopen ("rwq.txt" , "r");
    if (pFile == NULL)
        perror ("Error opening file");
    else {
        while ( fgets (mystring , 100 , pFile) != NULL )    //read a line every time

        {
            int len = strlen(mystring);
            if(mystring[len-1]=='\n')
                mystring[len-1] = '\0';

            char* tmp = (char*)malloc(100*sizeof(char));
            memcpy(tmp,mystring,len);//usage memcpy(dest, src, strlen(src)); 
            res[p++] = tmp;
            //puts (mystring);//put string every time
        }
        fclose (pFile);

    //  int re_len = sizeof(res)/sizeof(res[0]);//wrong way to get arry lenth
    //  printf("%d\n",re_len);
    for(int i=0;i

REF

  • C语言字符数组及其应用

  • 一维数组每次添加一个elements

char* s = "hello";  
int n = strlen(s);  
char a[100];  
for (int i=0;i

转载于:https://my.oschina.net/SnifferApache/blog/673700

你可能感兴趣的:(【C语言】从文件每次读入一行字符串,并把这些字符串添加到字符串数组中)