【问题标题】:Run time error in CC中的运行时错误
【发布时间】:2014-12-29 17:09:40
【问题描述】:

当我到达文件中间时,我的代码给出了运行时错误。 如果我更改 temp2 或 temp1 的值,那么它会在文件开头崩溃。 我无法理解我在此文件中所犯的错误。

它在一个有 100 行的小文件上运行流畅。

我正在做一个文件搜索项目,所以我需要存储具有整个驱动器目录的大文件。

#include<stdio.h>
#include<string.h>
#include<windows.h>
#include<conio.h>
char file[99999];
void brek(char *p, char *q);
void main()
{
    FILE *fp;
    int x = 0, y = 0;
    int a = 0, b = 0;
    int g = 0;
    char temp1[10000];          // temp1 is simply for jumping to the date against the given directory or file
        // the main array storing the lines is temp2.
     char temp2[1000][1000];

    system("chdir C:\\Users\\Faraz\\Documents && dir /s > dir.txt");
    fp = fopen("C:\\Users\\Faraz\\Documents\\dir.txt", "r");

    while ((y = getc(fp)) != EOF)
    {
        file[x] = y;
        x++;
    }
    fclose(fp);
    file[x] = '\0';
    puts(&file[0]);

    // <----the copying of the file to the string "file (globally declared)"is
    // done---->//

    getche();
    system("cls");

    // <-------------------start loop-------------------->//

    a = 0;
    while (file[a] != '\0')     // <-------starting of the loop
    {

        while (file[a] != '/')
        {
            temp1[a] = file[a];
            a++;
        }
        temp1[a] = '\0';

        a = a - 2;
        b = 0;
        while (file[a] != '\n')
        {
            temp2[g][b] = file[a];
            b++;
            a++;
        }
        temp2[g][b] = '\0';
        puts(&temp2[g][0]);

        g++;

    }
    // <-----------------end loop---------------------->//

}

【问题讨论】:

  • 当系统调用更好时,你为什么使用系统?
  • 你需要动态内存分配
  • 是的,上面的 cmets 适用,但您的主要问题是您在主循环中将变量 a 用于不同的事情:它同时索引 file 和 temp1。跨度>
  • @iharob 我是新手,动态内存分配对我有什么帮助?
  • @LeeDanielCrocker 它有助于丢弃目录列表中的附加信息并跳转到我可以处理文件或目录名称的部分

标签: c runtime-error file-handling c-strings


【解决方案1】:

试试这个

int 
main(int argc, char **argv)
{
    LPWIN32_FIND_DATAA fdFile;
    HANDLE hFind = NULL;
    const char *sPath = "C:\\Users\\Faraz\\Documents\\*.*";

    if((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE)
    {
        printf("no such directory %s\n", sPath);
        return -1;
    }

    do
    {
        printf("Directory: %s\n", fdFile->cFileName);
    }
    while(FindNextFile(hFind, &fdFile)); //Find the next file.

    FindClose(hFind); //Always, Always, clean things up!

    return 0;
}

【讨论】:

  • 我没有windows机器所以无法测试代码,把错误告诉我,我会尽力帮助你的。
  • @Zimad 现在试试,然后删除错误cmets。
  • 输出不存在目录
  • 您确定路径正确吗?是no directory exists 还是no such directory?
  • 很抱歉,没有这样的目录,是的,路径是正确的
【解决方案2】:

我发现的答案是,您根本无法在 512 mb 内存中加载 1gb 文件。 所以我们使用

在字符串顶部定义缓冲区大小
#define BUFFER_SIZE 512

并且使用 fgets 我们逐行读取文件,因此不会使操作系统分配的内存空间过载。

动态内存分配并不是解决我们问题的方法,因为我们开始使用堆空间。

【讨论】:

    猜你喜欢
    • 2012-07-28
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多