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

我一直试图通过首先对文件进行标记来读取文件中的数据。 在这个例子中,我已经做到这一点,它要求你先自己输入数据(我已经确定有效),然后读取它,但用空格标记。 因此,如果我要进入’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); 

任何帮助将非常感谢大家:)

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

main.c中

 #include  #include  #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! 
 // 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);