C程序执行后挂起

标签 c freeze

我是 C 编程新手。我制作了一个非常短的程序来合并文件夹中的所有文件。 该程序运行并产生正确的输出,但执行后它挂起,我必须手动终止它。 有什么想法吗?

这里重要的函数是scandirappend_to_file

/*
MERGE: Merges text files. Gives the ability to merge a list of files or all files in a 
directory with specified extension.
*/
#include <stdio.h>
#include <dirent.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>

/* Function prototypes */
int append_to_file(const char *filename, const char *outfilename); // Appends the contents of filename to outfilename
int scandir(char dirname[], char const *ext, char outfile[]); // Scans a directory for files of a specific extension and merges them
bool has_extension(char const *name, char const *ext);
void usage(); // Prints out usage information (help) to the console
void path_combine(char *dest, const char *path1, const char *path2); // Combines a directory name and filename to a single filepath

int main(int argc, char *argv[])
{    

    int i, // Counters
        nfiles; // Number of files merged

    if (argc == 4)
    {
        nfiles = scandir(argv[1], argv[2], argv[3]);      
        printf("Merged %s files\n", nfiles);

        return 0;  
    }
    else
    {
        printf("Wrong input, quitting");
        return 1;
    }

}

int append_to_file(const char *filename, const char *outfilename)
{
    FILE *infile, *outfile;
    char ch;
    infile = fopen(filename, "r");
    outfile = fopen(outfilename, "a");

    if (infile == NULL)
    {
        printf("Input file is empty, skipping...\n");
        return 1;
    }

    while ((ch = fgetc(infile)) != EOF)
        fputc(ch, outfile);

    fclose(infile);
    fclose(outfile);

    return 0;

}

int scandir(char dirname[], char const *ext, char outfile[])
/* Scans a directory and merges all files of given extension */
{
    DIR *d = NULL;
    struct dirent *dir = NULL;
    char filepath[strlen(dirname) + 255];
    int i = 0;   

    d = opendir(dirname);

    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {   
            if (has_extension(dir->d_name, ext))
            {   

                path_combine(filepath, dirname, dir->d_name);
                printf("%s\n", filepath);
                append_to_file(filepath, outfile);
                i++;
            }

        }
        closedir(d);
    }
    return i;
}


bool has_extension(char const *name, char const *ext)
{
    size_t len = strlen(name);
    return len > 4 && strcmp(name+len-4, ext) == 0;
}


void path_combine(char *dest, const char *path1, const char *path2)
{
    const char *last_char = path1;
    int append_sep = 0;
    char sep[] = "/";

#ifdef WIN32
    sep[0] = '\\';
#endif

    /* Find the last character in the first path*/
    while(*last_char != '\0')
        last_char++;

    /* If the last character is not a seperator, we must add it*/
    if (strcmp(last_char, sep) !=0)
    {
        append_sep = 1;
    }

    strcpy(dest, path1);
    if (append_sep)
        strcat(dest, sep);
    strcat(dest, path2);       

}


void usage()
{
    printf("\t=================\n");
    printf("\t      MERGE\n");
    printf("\t=================\n");
    printf("Merge two or more text files\n");
    printf("Usage:\n");
    printf("\tCall merge with a directory name and desired extension:\n");
    printf("\tmerge DIRNAME .csv OUTPUTFILE\n\n");

};

最佳答案

正如编译器警告您的那样(如果您使用 gcc -Wall -g 进行编译),请使用以下行:

    printf("Merged %s files\n", nfiles);

是错误的,因为nfiles是一个int。您可能想要

    printf("Merged %d files\n", nfiles);

了解undefined behavior 。你有一个。另请仔细阅读您正在使用的每个函数的文档,从 printf(3) 开始& fopen(3) & perror(3) & exit(3) 。不要忘记处理失败,例如:

FILE *infile, *outfile;
char ch;
infile = fopen(filename, "r");
outfile = fopen(outfilename, "a");

if (infile == NULL) {
    printf("failed to open %s (%s), skipping...\n", 
           filename, strerror(errno));
    return 1;
}
if (outfile == NULL) {
    perror(outfilename);
    exit(EXIT_FAILURE);
}

了解如何使用调试器 (gdb)。如果在 Linux 上,还可以使用 strace(1)valgrind .

关于C程序执行后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26406955/

相关文章:

c - Tint2 编译

C : Unexpected behaviour, 返回的列表错误?

Cocoa 在 TableView 中显示许多项目

Android 相机 Intent 不返回/锁定

html - 如何卡住页面的标题

JavaFX 程序在运行时锁定/卡住

c - 错误: How to fix the digitalWrite() error?

ubuntu - Racket 在 Google Colab 上挂起

android - Android WebView 中只有一个 javascript 警报,然后它停止响应

c - 我想在不使用字符串函数的情况下反转 c 中的字符串并更正字符串?