如何从用C每一行读第二和最后一句话 [英] How to read second and last words from each line in C

查看:135
本文介绍了如何从用C每一行读第二和最后一句话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据的文件

{0 /的数据1 的/,0×00,0,}为0xFF,

{0 /Data1/ , 0x00, 0, 0xFF},

{1 /的数据2 的/,0×00,0,}为0xFF,

{1 /data2/ , 0x00, 0, 0xFF},

{2 /的 DATA3 的/,0×00,0,}为0xFF,

{2 /data3/ , 0x00, 0, 0xFF},

{3 /的数据4 的/,0×00,0,}为0xFF,
...

{3 /data4/ , 0x00, 0, 0xFF}, ...

欲只打印每行的第二和最后一列。下面是code我的工作。其打印整行。如何编辑仅打印每行的第二和最后一列

I want to print only the second and last column of each line. Below is the code I worked on. Its printing the whole line. How to edit to print only the second and last column of each line.

#include<stdio.h>

#include<conio.h>

int main ()
{       
    char filename[] = "file.txt"; 

    FILE *file = fopen(filename, "r");

    if(file!= NULL)     
    {                           
        char line[128];                 

        while ( fgets( line, sizeof line, file)!= NULL)
        {                                           
            fputs ( line,stdout);                           
        }                                                       
        fclose(file);                           
    }                                               
    else                    
    {                               
        perror(filename);                   
    }                                           


    getch();                    

    return 0;                       
}        

请帮助!

由于一吨!

推荐答案

的sscanf()应该做的伎俩。

它使用一个格式字符串,就像printf()的,然后读取值到变量。

It uses a format string just like printf(), then reads the values into variables.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned int a, c, d, e;
    char b[101] = "";
    char filename[] = "file.txt";
    FILE *file = fopen(filename, "r");
    if (file != NULL) {
        char line[128];
        while (fgets(line, sizeof line, file) != NULL) {
            sscanf(line, "{%d %100s , %x, %d, %x}", &a, b, &c, &d, &e);
            printf("%d %X\n", d, e);
        }
        fclose(file);
    } else {
        perror(filename);
    }
    return 0;
}

这篇关于如何从用C每一行读第二和最后一句话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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