Este progtwig quiere leer de un archivo. El contenido del archivo es la cadena “Hola, mundo”. luego juzgue cada carácter de la cadena para ver si el carácter mayor o igual al carácter constante ‘e’, si el carácter cumple con la condición, que cambie el carácter a su carácter anterior en el orden alfabético (por ejemplo, cambio ‘b’ a ‘a’, ‘e’ cambia a ‘d’). Finalmente, envíe el contenido del archivo modificado a la pantalla.
La pregunta es ¿cómo funcionan fwrite y fread? ¿Por qué no puedo deshacerme de la variable pos2 para simplificar la expresión? Si alguien puede ayudar, muchas gracias!
#include int main() { FILE *fp; char s[20]; char t[20]; char transfer; int i; int pos; // storing the position of the file before reading from the file int pos1; // check the position of the file int pos2; // storing the position of the file after reading from the file #pragma region create a file named "Hello", write "Hello, world" into the file, close it if ((fp = fopen("Hello", "wb") )== NULL) { printf("can't open file\n"); exit(0); } strcpy(s, "Hello, world"); fwrite(s, sizeof(char)*20, 1, fp); fseek(fp, 0, SEEK_SET); fclose(fp); #pragma endregion create a file named "Hello", write "Hello, world" into the file, close it #pragma region read from the file named "Hello", deal with its current, write the change into the file. if ((fp = fopen("Hello", "rb+")) == NULL ) { printf("can't open file\n"); exit(1); } i = 0; while(i = 'e') // if the character greater or equal to 'e' minus 1. { transfer -= 1; } fseek(fp, pos, SEEK_SET); // back to the position where the character is read to change the char fwrite(&transfer, sizeof(char), 1, fp);// the position of the file moved to the next char // fseek(fp, pos2, SEEK_SET); // pos1 = ftell(fp); i++; } fseek(fp, 0, SEEK_SET); fclose(fp); #pragma endregion read from the file named "Hello", deal with its current, write the change into the file. #pragma region read from the file named "Hello", output the changed string if((fp = fopen("Hello", "rb")) == NULL) { printf("Can't open file\n"); exit(2); } fread(t, sizeof(char)*20, 1, fp); printf("The output is: %s \n", t); // the right output is (the two sentences above with pos2 in it is commented) : // The output is: Hdkkn,vnqkd // the wrong output is (the two sentences above with pos2 in it isn't commented): // The output is: Hddddddddddddddddddd烫烫烫烫Hello, world fseek(fp, 0, SEEK_SET); fclose(fp); #pragma endregion read from the file named "Hello", output the changed string system("pause"); }
En realidad no entendí el motivo por el que intentas comentar dentro / fuera de las 2 líneas. Porque nada cambia, ya sea que los comentes o los cometas. Ya te has deshecho de pos2 en tu código (que es lo que estás pidiendo).
Así que si usas el siguiente código para tu bucle while
pos = ftell(fp); // storing the position before reading from file fread(&transfer, sizeof(char), 1, fp); pos1 = ftell(fp); if (transfer >= 'e') // if the character greater or equal to 'e' minus 1. { transfer -= 1; } fseek(fp, pos, SEEK_SET); fwrite(&transfer, sizeof(char), 1, fp); i++;
luego se obtiene “La salida es: Hdkkn, vnqkd”, que es el resultado esperado.
También puede tomar cada línea del archivo a una matriz y realizar operaciones en ella y luego escribirla de nuevo en el archivo. De esta manera, podría ser más genérico y no tienes que usar números mágicos como “20”.
EDITAR:
Yo uso gcc 4.5.2 en mi plataforma Linux. No quiero hacer comentarios sobre otras plataformas, pero como mencioné antes, podría llevar la línea a un búfer y luego, después de la operación, podría escribirla de nuevo. Puedes intentar reemplazar el siguiente código con tu bucle while:
char line[20] = {0}; fread(line, sizeof(char), 20, fp); for(i = 0; i < strlen(line); i++) { if(line[i] >= 'e') line[i] -= 1; } fseek(fp, 0, SEEK_SET); fwrite(line, sizeof(char), strlen(line), fp);
De esta manera usted podría deshacerse de muchas variables. Es tu elección.