1

我一直在尝试通过首先标记文件来读取文件中的数据。在这个例子中,我已经做到了,它要求您首先在自己中输入数据(我已经确保它有效),然后将其读入但用空格标记。因此,如果我要输入“Hello World”,它应该返回:“Hello, World”。这是我的代码。

    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);

任何帮助将不胜感激伙计们:)

4

2 回答 2

2

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

主程序

#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;

}

文件.txt

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

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!
于 2013-05-19T06:41:58.690 回答
0
//  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);
于 2013-05-18T08:26:19.730 回答