запись и восстановление числа из файла

Discussion in 'С/С++, C#, Rust, Swift, Go, Java, Perl, Ruby' started by Satell, 6 Oct 2007.

  1. Satell

    Satell Elder - Старейшина

    Joined:
    13 Jan 2007
    Messages:
    91
    Likes Received:
    5
    Reputations:
    1
    нужно записать и восстановить время в файл в виде числа, как это сделать, у меня записанное и восстановленное время не совпадают

    #include <time.h>

    time_t curtime;

    curtime=time(NULL);

    printf("seichas: %s\n",ctime(&curtime));

    FILE *file;
    char* file_name = "d:\\time.txt";
    char load_string[50];
    file = fopen( file_name,"w");
    fwrite(&curtime,sizeof(time_t),1,file);
    fclose(file);



    file = fopen(file_name,"r");
    if(file != 0)
    {
    fgets(load_string, 50,file);
    time_t b=(time_t) load_string;
    printf("seichas: %s\n", ctime(&b));
    }
    fclose(file);
     
  2. _Great_

    _Great_ Elder - Старейшина

    Joined:
    27 Dec 2005
    Messages:
    2,032
    Likes Received:
    1,118
    Reputations:
    1,139
    а с какой радости должно совпадать если ты так пишешь?


    FILE* fp;
    time_t ctime;

    ctime = time(0);
    printf("Current time: %d\n", ctime);

    fp = fopen("time.bin", "w");
    fwrite( &ctime, sizeof(ctime), 1, fp);
    fclose(fp);

    ctime = 0;
    fp = fopen("time.bin", "r");
    fread( &ctime, sizeof(ctime), 1, fp);
    printf("Current time (from file): %d\n", ctime);
    fclose(fp);
     
    #2 _Great_, 6 Oct 2007
    Last edited: 6 Oct 2007
  3. Kaimi

    Kaimi Well-Known Member

    Joined:
    23 Aug 2007
    Messages:
    1,732
    Likes Received:
    809
    Reputations:
    231
    Так сойдет?:

    Code:
    #include <iostream.h>
    #include <fstream.h>
    #include <time.h>
    #include <conio.h>
    int main()
    	{
    	time_t t;
            int a=0,i=0;
            cout<<"Make your decision: 1 - write; 2 - read"<<endl;
            cin>>a;
            switch(a)
                    {
    	        case 1: {ofstream out("test.txt");
                            if(!out) { cout<<"Error"; return 1; }
    	                out<<t;
    	                out.close(); break;}
                    case 2: {ifstream in("test.txt");
                            if(!in) { cout<<"Error"; return 1;}
                            in>>i;
                            in.close(); break;}
                    }
    
            cout<<"Out: "<<t<<endl;;
            cout<<"In: "<<i<<endl;;
    	getch();
    
    	}
    
    _Great_: Ему, вероятно, нужно было на Си...
     
    _________________________
  4. _Great_

    _Great_ Elder - Старейшина

    Joined:
    27 Dec 2005
    Messages:
    2,032
    Likes Received:
    1,118
    Reputations:
    1,139
    Kaimi
    Значение t при записи в файл у тебя не определено.