Fisiere C/C++

Intrebari despre limbajul C++, standardul C++, STL, OOP in C++ sau alte subiecte nelegate de VisualC++
Post Reply
serbug
Junior
Junior
Posts: 3
Joined: 16 Mar 2016, 00:52
Judet: Iaşi

Fisiere C/C++

Post by serbug » 30 Mar 2016, 02:52

Stie cineva cum as putea modifica datele dintr-un fisier ?


Mai jos e codul unde am incercat singur, dar fara succes !


#include "iostream"

using namespace std;

struct baza { char nume[30], prenume[30]; int media; };

int main()
{
int i, n;
char I[30], L[30];
FILE *f;
struct baza B[10];
long int pos;


printf("Introduceti numarul de inscrieri:\n"); scanf_s("%d", &n); printf("\n");
printf("Introduceti datele:\n\n");
for (i = 0; i < n; i++)
{
cout << "Nume: "; cin >> B.nume;
cout << "Prenume: "; cin >> B.prenume;
cout << "media:"; scanf_s("%d", &B.media); printf("\n\n");
}
f = fopen("sursa.txt", "w");
for (i = 0; i < n; i++)
{
fwrite(&B, sizeof(B), 1,f);
}
fclose(f);


f = fopen("sursa.txt", "r"); i = 0;

while (fread(&B, sizeof(B), 1, f) == 1)
{
printf("%s %s %d\n", B.nume, B.prenume, B.media); i++;
}
fclose(f);
printf("Introduceti numele cautat:");
cin >> I;

f = fopen("sursa.txt", "rb+"); i = 0;
while (fread(&B[i], sizeof(B[i]), 1, f) == 1)
{
if (strcmp(B[i].nume, I) == 0)
{
pos = ftell(f) - sizeof(B[i]);

printf("%ld\n", pos);
printf("Introduceti un nou nume:\n");
cin >> L;
strcpy(B[i].nume, L);
if (fseek(f, pos, SEEK_SET)==0);
//printf("%s %s %d\n", B[i].nume, B[i].prenume, B[i].media);
fwrite(&B[i], sizeof(B[i]), 1, f);
printf("%s %s %d\n", B[i].nume, B[i].prenume, B[i].media);
fclose(f);
break;

}
}
f = fopen("sursa.txt", "r");
i = 0;
while (fread(&B[i], sizeof(B[i]), 1, f) == 1)
{
printf("%s %s %d\n", B[i].nume, B[i].prenume, B[i].media); i++;
}
fclose(f);
return 0;
}



Post Reply