Click here to Skip to main content
15,889,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to read a formating hour ( HH:MM:SS) from a text file in c and pass every number until to fine ':' to three ints : h , m, s

How can be possible?

I wrote the code to pass the string to a char but i don't know if that's the best option.

C
/* Source Code to read a text of string from a file. */

#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
	
   char c[1000];
   FILE *input;
   if ((input = fopen("time.in","r"))==NULL){
       printf("Error! opening file");
       exit(1);         /* Program exits if file pointer returns NULL. */
   }
   
   fscanf(input,"%[^\n]",c);
   printf("Data from file:\n%s",c);
   fclose(input);
   
   
   
   return 0;
}
Posted
Comments
nv3 18-Dec-14 9:52am    
Your fscanf is overly complex. I would simply use fgets.
Then, for the parsing of the string, I would use three calls to strtok to subdivide the string into its components. Then convert each component with strtol.
[no name] 18-Dec-14 10:36am    
+1 on the fgets which is safer. The fscanf example may overflow.
[no name] 18-Dec-14 12:02pm    
I couldn't do it. please help me more!
barneyman 18-Dec-14 17:42pm    
if(fgets(c,1000,input)){ int a,b,c; sscanf("%d:%d:%d",&a,&b,&c); } would be simpler, but using strok would be safer

1 solution

it is so easy if your google some minutes:
C++
int hour, min, sec;
fscanf( input, "%ld:%ld:%ld", &hour, &min, &sec);
 
Share this answer
 
Comments
Richard MacCutchan 19-Dec-14 5:42am    
%ld for ints?
Andreas Gieriet 19-Dec-14 6:07am    
My 5.
You might improve by
if (fscanf(...) != 3) { /* handle error...*/ }
Cheers
Andi

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900