首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

c语言 读取资料内容?把内容存放到数组指针当中

2013-07-08 
c语言 读取文件内容?把内容存放到数组指针当中.我在当前目录有一个abc.txt文件里面有许多信息, 以[]截

c语言 读取文件内容?把内容存放到数组指针当中.
我在当前目录有一个abc.txt文件里面有许多信息, 以"["    "]"   截取这2个中间的内容比如:abc.txt 内容如下 [aaaaa][bbbbb] 然后用c语言程序把 这2个  存放到数组指针中.,去掉 []
[解决办法]

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 200

char *change[SIZE];
int num = 0;
void fun(char *p) 
{
    char *q; 
    while(*p == '[') {
        change[num++] = ++p;
        while(*p++!=']');
        *(p-1) = '\0';
    }   

}
int main(void)
{
    int fd,ret = 0;
    int i;
    char buf[SIZE];
    fd = open("./abc.txt",O_RDWR);
    if(ret < 0) {
        perror("open fail");
        exit(1);
    }   
        ret = read(fd , buf , sizeof(buf));
    printf("%s\n",buf);
    fun(buf);
        
    for(i = 0; i < num; i++)
        printf("%s\n",change[i]);
    return 0;
}

[解决办法]
fun函数
void fun(char *p)
{
char separater[] = "[]";
change[0]=strtok(p, separater);
    for(num=0;change[num] != NULL;)
change[++num] = strtok( NULL, separater );
}

[解决办法]
用fscanf的正则表达就可以了
#include <stdio.h>

int main(int argc, char* argv[])
{
FILE *fp1;
int i;
char other[20];
char a[5][20] = {0};

if((fp1 = fopen("abc.txt","r")) == NULL)
{
printf("open file error\n");
return -1;
}
for (i=0; i<5; i++)
{
fscanf(fp1, "%[^0-9a-zA-Z]s", &other);
if (fscanf(fp1, "%[0-9a-zA-Z]s", a[i]) == EOF )
{
break;
}
}
for (; i>0; i--)
{
printf("%d = %s\n", i-1, a[i-1]);
}
return 0;
}

输出
1 = bbbbb
0 = aaaaa

热点排行