简体   繁体   English

从C中的文件打印标记化数据

[英]Printing tokenized data from file in C

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'. 因此,如果我要输入“ Hello World”,则应返回:“ 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 :) 任何帮助将不胜感激的家伙:)

Below is the c version. 下面是c版本。 However, I must say that I prefer the c++ version. 但是,我必须说我更喜欢c ++版本。 :-) https://stackoverflow.com/a/3910610/278976 :-) https://stackoverflow.com/a/3910610/278976

main.c 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 file.txt的

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

linux shell Linux外壳

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!
//  fread(buffer, strlen(number)+1, 1, fp);
    fscanf(fp, "%s", buffer);//read "hello"
    printf("%s, ", buffer);
    fscanf(fp, "%s", buffer);//read "world"
    printf("%s\n", buffer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM