首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >strcpy崩溃程序

strcpy崩溃程序
EN

Stack Overflow用户
提问于 2022-01-06 20:27:57
回答 1查看 123关注 0票数 2

我创建了一个程序来导入日期和时间条目(例如。29/11/2021-15:33:56),并将它们存储在数组中。然后,我们被要求创建一个函数(timeStampToSeconds)来将它们转换为长ints。一旦我们有了长的ints,我们就必须将条目作为秒进行比较,并使用选择排序将这些条目从最早的放到最新的。

我已经创建了下面的程序来完成这个任务,但是当我到达strcpy函数时,程序就会崩溃。

我看不出我是如何不正确地使用这个,但肯定是遗漏了什么。如果有人对如何使用它来交换我对应的char数组条目有任何建议,我们将不胜感激。为此,我可能需要使用一个完全不同的功能。

代码语言:javascript
复制
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

long int timeStampToSeconds(char array[]);

int main(void) {
    char array[50][20];
    long int intarray[50];

    char input[12], filename[] = "Timestamps", outputfile[40], file_ext[] = ".dat", temp[20];
    int i = 0, n = 0, j, x = 0, y = 0, o = 0, f = 1, result = 1;
    double datetime = 0;

    while (result != 0) {
        printf("\nPlease enter the names of the required Input file: \n");
        scanf("%10s", input);

        /* compare input & filename */
        result = strcmp(input, filename);
        
        if (result == 0) {
            printf("Input accepted!\n");
        } else
            printf("File name not found.Please try again!\n");
    }

    printf("Please enter the name of the sorted Output file to be created: \n");
    scanf("%s", &outputfile);
    strncat(&outputfile, &file_ext, 4);  /* appends file extension characters to outputfile variable characters */

    FILE *Ptr = NULL;
    FILE *cfPtr = (char *)malloc(100 * sizeof(char));

    if ((cfPtr = fopen("Timestamps.dat", "r")) == NULL) {
        printf("File could not be opened\n");
    }

    while (!feof(cfPtr)) {
        for (i = 0; i < 50; ++i) {
            for (j = 0; j < 20; ++j) {
                array[x][j] = fgetc(cfPtr);
                y++;
            }
            x++;
        }
    }

    fclose(cfPtr);

    for (int p = 0; p < 50; p++) { // loop to control number of passes
        int l;
        for (l = 0; l < 50; ++l, ++f) {   /* loop to control number of comparisons per pass */
            n = timeStampToSeconds(array[l]); /*convert to long int to compare 2 strings*/
            o = timeStampToSeconds(array[f]);

            if(n > o) {
                strcpy(temp, array[f]); /* selection sort algorithm */
                strcpy(array[f], array[l]);
                strcpy(array[l], temp);
            }
        }
    }

    if ((Ptr = fopen(outputfile, "w+")) == NULL) {
        printf("File could not be opened\n");
    }

    for (int l = 0; l < 50; ++l) {
        fprintf(Ptr, "%ld\n", intarray[l]);
    }
    fclose(Ptr);

    return 0;
}

long int timeStampToSeconds(char array[]) {
    
    long int day, mon, yr, hr, min, sec;
    long int totaldays, totalmonths, total;
    
    day = atol(array);
    mon = atol(array + 3);
    yr = atol(array + 6);
    hr = atol(array + 11);
    min = atol(array + 14);
    sec = atol(array + 17);

    hr = hr * (60 * 60); /*converts hours to seconds*/
    min = min * 60;

    day = day * 86400;
    mon = mon * 2628000;
    yr = (yr - 2000) * 31557600; /* total seconds elapsed in yrs from 2020 */

    totaldays = hr + min + sec; /* total seconds from hr/min/sec */
    totalmonths = day + mon + yr; /* total seconds from dd/mm/yy */

    total = totaldays + totalmonths;

    return total;
}
EN

回答 1

Stack Overflow用户

发布于 2022-01-06 20:40:49

您将20个字节读入数组array[x],但没有在末尾设置一个空终止符,因此它们不是正确的C字符串,strcpy可能会将超过20个字节复制到tmp中,调用未定义的行为。

还有其他问题:

读取循环使用incorrectly.

  • the timeStampToSeconds函数,不处理实际月长和闰年。

以下是修改后的版本:

代码语言:javascript
复制
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

long int timeStampToSeconds(const char array[]);

int main(void) {
    char array[50][21];
    long int intarray[50];
    char input[12];
    char filename[] = "Timestamps";
    char outputfile[40];
    char file_ext[] = ".dat";
    char temp[20];
    int i = 0, n = 0, j, x = 0, y = 0, o = 0, f = 1, result = 1;
    double datetime = 0;

    while (result != 0) {
        printf("\nPlease enter the name of the required Input file: \n");
        if (scanf("%11s", input) != 1)
            return 1;

        /* compare input & filename */
        result = strcmp(input, filename);
        
        if (result == 0) {
            printf("Input accepted!\n");
        } else {
            printf("File name not found.Please try again!\n");
        }
    }

    printf("Please enter the name of the sorted Output file to be created: \n");
    scanf("%15s", &outputfile);
    strcat(outputfile, file_ext);  /* append file extension */

    FILE *Ptr;
    FILE *cfPtr;

    if ((cfPtr = fopen("Timestamps.dat", "r")) == NULL) {
        printf("File could not be opened\n");
        return 1;
    }

    for (x = 0; x < 50; x++) {
        if (fread(array[x], 1, 20, cfPtr) != 20)
            break;
        array[x][20] = '\0'
    }
    fclose(cfPtr);

    for (int p = 0; p < x; p++) { // loop to control number of passes
        int l;
        for (l = 0; l < x; ++l, ++f) {   /* loop to control number of comparisons per pass */
            n = timeStampToSeconds(array[l]); /*convert to long int to compare 2 strings*/
            o = timeStampToSeconds(array[f]);

            if (n > o) {
                strcpy(temp, array[f]); /* selection sort algorithm */
                strcpy(array[f], array[l]);
                strcpy(array[l], temp);
            }
        }
    }

    if ((Ptr = fopen(outputfile, "w+")) == NULL) {
        printf("File could not be opened\n");
        return 1;
    }

    for (int l = 0; l < x; ++l) {
        fprintf(Ptr, "%ld: %s", timeStampToSeconds(array[l]), array[l]);
    }
    fclose(Ptr);

    return 0;
}

long int timeStampToSeconds(const char array[]) {
    static const int mdays[12] = {
        31,
        31+28,
        31+28+31,
        31+28+31+30,
        31+28+31+30+31,
        31+28+31+30+31+30,
        31+28+31+30+31+30+31,
        31+28+31+30+31+30+31+31,
        31+28+31+30+31+30+31+31+31,
        31+28+31+30+31+30+31+31+31+30,
        31+28+31+30+31+30+31+31+31+30+31,
        31+28+31+30+31+30+31+31+31+30+31+30,
    };
    int day, mon, yr, hr, min, sec;
    
    /* parse 29/11/2021-15:33:56 format */
    if (sscanf("%d/%d/%d-%d:%d:%d", &day, &mon, &yr, &hr, &min, &sec) != 6) {
        /* invalid format */
        return -1;
    }

    /* compute the number of seconds since midnight */    
    sec += min * 60 + hr * 3600;

    /* compute the number of days since Jan 1st, 2000 */
    day += (yr - 2000) / 4 * (366 + 365 + 365 + 365);
    yr %= 4;
    day += yr * 365;
    if (yr > 0 || mon > 2)
        day += 1;
    day += mdays[mon - 1];
​   return sec + day * 86400L;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70613249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档