【C语言】从文件每次读入一行字符串,并把这些字符串添加到字符串数组中
2016-05-11 22:48
190 查看
问题描述
从文件每次读入一行字符串,并把这些字符串添加到字符串数组中测试文件rwq.txt
hello jjjjj ddddd 44444l hello hello jjjjj ddddd jjjjj ddddd
实现
读入一行之后需要处理末尾的\n,改成
\0
使用char* 数组来表示二维char数组
#include <stdio.h> #include<string.h> 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<p;i++) printf("%s\n",res[i]); } return 0; }
REF
C语言字符数组及其应用一维数组每次添加一个elements
char* s = "hello"; int n = strlen(s); char a[100]; for (int i=0;i<n;i++) { a[i]=*(s++); }
相关文章推荐
- C++第五次实验
- 【c++】第十二周上机实践作业 项目 1-3
- c++ 作业5
- C++11新特性学习笔记(一)
- Wormholes
- GNU C 、ANSI C、标准C、标准c++区别和联系
- 【LeetCode-223】 Rectangle Area(C++)
- 【c++】第十二周上机实践作业 项目 1-2
- C++回车换行时停止读入
- C++实验5-成绩
- Qt:使用C++还是QML
- 【c++】第十二周上机实践作业 项目 1-1
- C++-作业五
- C++指针详解
- C++新特性
- [转]c++中的类型及运算
- android NDK开发编译C++文件出现Type 'jint' could not be resolved和Unresolved inclusion: <jni.h>的解决办法
- C++第五次作业
- 【C语言】反序数
- C++第5次作业