从C中的文件打印标记化数据 [英] Printing tokenized data from file in C

查看:97
本文介绍了从C中的文件打印标记化数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试通过首先对文件进行标记来从文件中读取数据.在此示例中,我这样做了,因此它要求您首先自己输入数据(我确定它可以正常工作),然后读取它,但用空格标记.因此,如果我要输入"Hello World",则应返回:"Hello,World". 这是我的代码.

I've been trying to read in data from a file by tokenizing it first. In this example, I've made it so that it asks you to first input the data in yourself (which I've made sure works), and then read it in but tokenize with spaces. So if I was to enter 'Hello World' it should return: 'Hello, World'. Here's my code.

    char fname[] = "myfile";
FILE *fp;
fp = fopen(fname, "w+");
char buffer[20];

sprintf(prompt, "Enter your string: ", MAX_TAN_INPUT);
getString(number, MAX_TAN_INPUT, prompt);
printf("\n");

if (fp == NULL)
{
    fprintf(stderr, "Unable to open file %s\n", fname);
}
else
{
    printf("YAYYY. It opened!\n");

    fprintf (fp, "%s\n", number);

    fseek(fp, SEEK_SET, 0);
    fread(buffer, strlen(fp)+1, 1, fp);
    printf("%s\n", buffer);
    {
        /* No more data read. */
    }
}

printf ("HERE\n");

fclose(fp);

任何人的帮助都将不胜感激:)

Any help would be greatly appreciated guys :)

推荐答案

下面是c版本.但是,我必须说我更喜欢c ++版本. :-) https://stackoverflow.com/a/3910610/278976

Below is the c version. However, I must say that I prefer the c++ version. :-) https://stackoverflow.com/a/3910610/278976

main.c

#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 1024


int main( int argc, char** argv ){

    const char *delimiter_characters = " ";
    const char *filename = "file.txt";
    FILE *input_file = fopen( filename, "r" );
    char buffer[ BUFFER_SIZE ];
    char *last_token;

    if( input_file == NULL ){

        fprintf( stderr, "Unable to open file %s\n", filename );

    }else{

        // Read each line into the buffer
        while( fgets(buffer, BUFFER_SIZE, input_file) != NULL ){

            // Write the line to stdout
            //fputs( buffer, stdout );

            // Gets each token as a string and prints it
            last_token = strtok( buffer, delimiter_characters );
            while( last_token != NULL ){
                printf( "%s\n", last_token );
                last_token = strtok( NULL, delimiter_characters );
            }

        }

        if( ferror(input_file) ){
            perror( "The following error occurred" );
        }

        fclose( input_file );

    }

    return 0;

}

file.txt

Hello there, world!
How you doing?
I'm doing just fine, thanks!

Linux shell

root@ubuntu:/home/user# gcc main.c -o example
root@ubuntu:/home/user# ./example
Hello
there,
world!

How
you
doing?

I'm
doing
just
fine,
thanks!

这篇关于从C中的文件打印标记化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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