C程序打印垃圾值

时间:2018-05-22 18:00:00

标签: c file

我的主要问题是,当我运行该程序时,它不起作用,并且我的屏幕上出现了runnig time错误。有人能解释我这个问题并帮助我吗? * argv [i]是地址而忽略了我没有任何免费使用我的mallocs的事实。

int main(int argc, char** argv)
{
FILE* file = 0;
file = fopen(argv[1], "r");
int numOfLines = countLines(file), i = 0, ch = 0, j = 0, flag = 0;
char** content;
content = (char**)malloc(numOfLines * sizeof(char*));
int* charsInLine = (int*)malloc(numOfLines * sizeof(int));
countCharsInLine(file, charsInLine);
fseek(file, 0, SEEK_SET);
for (i = 0; i < numOfLines; i++)
{
    int lenOfFile = 0;
    fseek(file, 0, SEEK_END);
    lenOfFile = ftell(file);
    content[i] = (char*)malloc(charsInLine[i] * sizeof(char) + 1);
    content = fread(content, 1, lenOfFile, file);
}
for (i = 0; i < numOfLines; i++)
{
    printf("%d string = %s", i,content[i]);
}
fclose(file);
getchar();
return 0;
}

1 个答案:

答案 0 :(得分:1)

我将假设countLinescountCharsInLine正常工作

以下是带注释的更新代码

int main(int argc, char** argv)
{
   FILE* file fopen(argv[1], "r");
   if (file == NULL) {
      // Output some error message
      return EXIT_FAILURE;
   }

   int numOfLines = countLines(file); // I assume this rewinds.

   char** content;
   content = malloc(numOfLines * sizeof(char*)); // Do not need a cast

   int* charsInLine = malloc(numOfLines * sizeof(int));

   countCharsInLine(file, charsInLine);

   rewind(file); // Easier to read the fseek

   for (int i = 0; i < numOfLines; i++)
   {
      content[i] = malloc(charsInLine[i] + 1); // * sizeof(char) - Do not need this as sizeof(char) is defined as 1
      // Reading one item of size charsInLine[i]
      if (fread(content[i], charsInLine[i], 1, file) != 1) {
         // Some error has occurred
         fclose(file);
         return EXIT_FAILURE; 
      }
      content[i][charsInLine[i]] = 0; // Add null character

      int ch = fgetc(file);
      if (ch != '\n' && ch != EOF) { // Should be reading either the new line at the end of the line, or EOF
         // Some error has occurred
         fclose(file);
         return EXIT_FAILURE; 
      }
   }
   fclose(file);
   // Should free up the stuff that is malloced - I leave that up to you
   return EXIT_SUCCESS;
}