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

如何读取文件中上字符串

2012-05-01 
怎么读取文件中上字符串在一个文件如IP.txt中保存了大量的IP地址,相邻的两个IP地址以一个空格分开。如192.1

怎么读取文件中上字符串
在一个文件如IP.txt中保存了大量的IP地址,相邻的两个IP地址以一个空格分开。如192.168.115.32 192.168.115.33
怎样才能把它们依次读入到char IPStrin[32]这个数组里。

f=fopen("IP.txt","r");
fprintf(f,"%s",IPString);
试过了,不行,还有其他办法吗???

[解决办法]
f=fopen("IP.txt","r");
while(!feof(fp))
{
fscanff(f,"%s",IPString);
puts(IPString);
}

[解决办法]

C/C++ code
#include <stdio.h>#include <stdlib.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>/* *             const char *inet_ntop(int af, const void *src, *                                          char *dst, socklen_t size); * */int make_random_ip(FILE *out, int num) {        int i, rd;        struct in_addr in;        char str_ip[20];        const char *ret = NULL;        if (out == NULL || num < 1) {                return -1;        }        srand((unsigned int)time(NULL));        for (i = 0; i < num; ) {                rd = rand();                in = *(struct in_addr*)&rd;                ret = inet_ntop(AF_INET, (const void*)&in, str_ip, sizeof(str_ip));                if (ret) {                        if (fprintf(out, "%s ", ret) < 0) {                                return -1;                        }                        ++ i;                }        }        return 0;}int main(int argc, char* const argv[]) {        FILE *out = NULL;        if ((out = fopen("./random_ip.txt", "w+")) == NULL) {                fprintf(stderr, "[ERROR] %s\n", __FUNCTION__);                exit(1);        }        if (!make_random_ip(out, 10)) {                fseek(out, SEEK_SET, 0);                char str_ip[20];                while (fscanf(out, "%s", str_ip) == 1) {                        printf("%s\n", str_ip);                }        }        return 0;} 

热点排行