C程序在增加文件中的数字时读/写文件

时间:2017-07-16 02:21:21

标签: c file-io

我正在从文件中读取时间,然后尝试将读取时间转换为秒。是否有更简单的方法来转换时间戳?我的方法似乎效率低下。在写入文件时,您认为什么是最好的方法?

示例文件

My test file
00:19.1 123456
00:35.4 testing whitespace end

Desired Output
1: My test file
2: 00:19.1
3: 00:35.4

代码:

#include <stdio.h>

#define MAXC 1024                                                                   // define constants, don't use magic number in code
#define MAXN 40
int main (int argc, char **argv) {

    char buf[MAXC] = "";                                                            // buffer to hold each line -- size as reqd
    char filename[MAXN];
    int line = 1;
    int replace_line;
    FILE *fp, *fp2;
    printf("Please enter a file name: ");
    scanf("%s",&filename);
    fp = fopen(filename,"r+");
    if (!fp)                                                                        // validate file open for reading
    {
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }
    //printf("Enter a increment of time: ");
    //scanf("%d", &increment);
    while (fgets (buf, sizeof buf, fp))                                             // read each line in file
    {
        char et[MAXC] = "";                                                         // buffer for holding time
        char etR[MAXC] = "";
        char time[7] = "";
        int filler = 0;

        if (line == 1)                                                              // if 1st line, just print
        {
            printf ("%d : %s", line, buf);                                          // note: \n included by fgets
            //fprintf(fp2,"%s",buf);
        }   // end of if first line
        else
        {
            if (sscanf (buf, "%s", et) != 1)                                        // parse up to first whitespace
            {
                fprintf (stderr, "error: invalid conversion, line %d\n", line);
                return 1;
            }
            printf ("%d : %s\n", line, et);                                         //output elapsed time only
            while(filler < 7)
            {
                time[filler] = et[filler];
                filler++;
            }
            time[1] = time[1] - '0';    //Leading Minute (error if over 6)
            time[2] = time[2] - '0';    //Minute
            time[4] = time[4] - '0';    //Leading Second (Add to minute if over 6)
            time[5] = time[5] - '0';    //Second (Add to LS if over 9)
            time[7] = time[7] - '0';    //fraction of a second (Add to S if over 9)
            float timeInSeconds;
            char minuteHolder[2];
            sprintf(minuteHolder,"%d%d",time[1],time[2]);
            int minute;
            minute = (minuteHolder[0]*10) + minuteHolder[1];
            printf("\n%d\n",minute);
            //getting 539 , minutes on every line???

        }   //end of else
        line++;                                                                     // increment line count
    }   // end of while parsing file
    rewind(fp);
    if (fp != stdin)                                                                // close file if not stdin
    {
        fclose (fp);
    }
    return 0;
}

2 个答案:

答案 0 :(得分:0)

转换源字符串:“00:19.1 123456” 到dest字符串:“1. 00:19.1”

  • 1st:我们应该找到黑色字符pos:
         * char pblack = strchr(buf,'');
         现在pblack指向“123456”。
  • 2nd:我们将旧字符串设置为新字符串:
         因为一个字符串以'\ 0'结尾,即      所以我们设置: pblack [0] ='\ 0';

现在,我们有了代码:

#include <stdio.h>

#define MAXC 1024                                                                   // define constants, don't use magic number in code
#define MAXN 40
int main(int argc, char **argv) {

char buf[MAXC] = "";                                                            // buffer to hold each line -- size as reqd
char filename[MAXN];
int line = 1;
int replace_line;
//FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
//FILE *fp = fopen("test.txt","r");
FILE *fp, *fp2;
printf("Please enter a file name: ");
scanf("%s", &filename);
fp = fopen(filename, "r+");
//fp2 = fopen("datadump.txt","w");
if (!fp)                                                                        // validate file open for reading
{
    fprintf(stderr, "error: file open failed '%s'.\n", argv[1]);
    return 1;
}
//printf("Enter a increment of time: ");
//scanf("%d", &increment);
while (fgets(buf, sizeof buf, fp))                                             // read each line in file
{
    char et[MAXC] = "";                                                         // buffer for holding time
    char etR[MAXC] = "";
    char time[7] = "";
    int filler = 0;

    if (line == 1)                                                              // if 1st line, just print
    {
        printf("%d : %s", line, buf);                                          // note: \n included by fgets
                                                                               //fprintf(fp2,"%s",buf);
    }   // end of if first line
    else
    {
        char *pblack = strchr(buf, ' '); // get chr ' ' pos
        pblack[0] = 0;                   // set ' ' to '\0', get the new string 
        printf("%d : %s\n", line, buf);
    }   //end of else
    line++;                                                                     // increment line count
}   // end of while parsing file
rewind(fp);
//fp2 = fopen("replica.c","w");
//replacement code
/*
flcose(fp);
fclose(fp2);
remove(filename(;
rename("replica.c",filename);
//if you to show them new file fflush stdin and repeat while
//fp = fopen(filename, "r");
//while loop
*/
if (fp != stdin)                                                                // close file if not stdin
{
    fclose(fp);
    //fclose (fp2);
}
return 0;

}

答案 1 :(得分:0)

如果时间格式为增量后的相同,则可以将时间字段替换为fseek而不重写整个文件。
显示了一个总体示例。请更改详细信息 试试这个

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAXC    1024 //input buffer size
#define MAXLINE 1024 //max number of line

int main (int argc, char **argv) {
    char filename[FILENAME_MAX+1+1];//+1: newline, +1: NUL
    char buf[MAXC] = "";
    char time_field[7+1];//mm:ss.s, +1: NUL
    unsigned char ch;
    long pos[MAXLINE];//save file positions
    int line = 0;     //start with 0 in program
    int replace_line; //input replace line number
    int increment;    //input incremant second.
    FILE *fp;

    printf("Please enter a file name: ");
    fgets(filename, sizeof filename, stdin);
    filename[strcspn(filename, "\n")] = 0;//chomp newline
    fp = fopen(filename, "r+");
    if (!fp){
        fprintf (stderr, "error: file open failed '%s'.\n", filename);
        return 1;
    }
    //display file & store file position each line
    pos[line] = ftell(fp);
    while (fgets (buf, sizeof buf, fp)){
        if(++line == MAXLINE){
            fprintf (stderr, "error: file too long.\n");//Need change the program. expand array or use malloc and realloc
            return 2;
        }
        pos[line] = ftell(fp);
        if (!isdigit(ch = *buf)){//If it does not start with a numerical value Output as it is
            printf("%d : %s", line, buf);  //note: \n included by fgets
        } else {
            if(sscanf(buf, "%7s%c", time_field, &ch)==2 && isspace(ch)){
                printf ("%d : %s\n", line, time_field);
            } else {
                fprintf (stderr, "error: invalid time format '%s'", buf);
                return 3;
            }
        }
    }
    printf("Enter a number of edit line: ");
    scanf("%d", &replace_line);

    printf("Enter a increment of time: ");
    scanf("%d", &increment);//sec

    if(fseek(fp, pos[replace_line-1], SEEK_SET)==0){//-1: 0 start in program, 1 start in input
        int m, s, ds, seconds;
        fscanf(fp, "%s", time_field);
        if(sscanf(time_field, "%d:%d.%d", &m, &s, &ds)!=3){
            fprintf (stderr, "error: invalid time format '%s' at %d line.\n", time_field, replace_line);
            return 3;
        }
        seconds = m * 60 + s + increment;
        m = seconds / 60;
        s = seconds % 60;
        if(m > 99 || seconds < 0){
            fprintf (stderr, "error: Can't change time format.\n");//It is necessary to rewrite the whole file.
            return 4;
        }
        fseek(fp, pos[replace_line-1], SEEK_SET);
        fprintf(fp, "%02d:%02d", m, s);fflush(fp);
    } else {
        fprintf (stderr, "error: file seek failed to '%d' line.\n", replace_line);
        return 5;
    }
    fclose(fp);
    return 0;
}