简体   繁体   中英

Not enough memory error in C

I am very new to C. I am creatin a file in C. But when i am trying to run below code I am getting Not enough memory error. i can not understand the problem. I cleared my temp folder but still the error exists. Any help please.

File *logfile;
logfile = fopen ("sample.txt","a+");
printf("\n logfile=%d\n",logfile);
if (!logfile)
 {
  perror("Error");
  exit(EXIT_FAILURE);
 }

You should always ask your compiler to give you all the warnings it can. With gcc it means passing -Wall -Wextra options to the gcc compiler.

If you did that, your compiler would have caught a lot of mistakes (by issuing warning or error messages):

  1. You are missing the #include <stdio.h> directive
  2. You should declare FILE* logfile; not File *logfile; Cases in identifiers are significant.
  3. Your call to printf is wrong, because logfile is not an int as the %d format specifier wants. It is a pointer (to an abstract data structure), so if you want to printf it, use %p . Be awre that you won't know much about an fopen -ed FILE* handle from its address (what only should matter to you is if the result of fopen is NULL or not).

A general advice is to improve your source code till you get no more warnings from the compiler.

You should also learn to use a debugger (like gdb ). Then compile with debugging information, eg gcc -Wall -Wextra -g yoursource.c -o yourprog

If you are on a Linux system (on which gcc and gdb are very usual tools), the valgrind , strace and ltrace utilities are often useful.

logfile should be of type FILE * - change:

File *logfile;

to:

FILE *logfile;

and also change:

printf("\n logfile=%d\n",logfile);

to:

printf("\n logfile=%p\n",logfile);

I'm assuming you actually wanted to output the contents of the file, but if you really wanted to see the pointer, Paul R's post is probably more what you're after. Having said that, it's been a while since I've done this in C, but I think you'd want something along these lines:

#include <stdio.h>
#include <stdlib.h>

#define BUFFER 1000

int main(void)
{
  FILE *logfile = fopen("sample.txt", "r");
  char buffer[BUFFER];

  if (!logfile)
  {
    printf("Error\n");
    exit(EXIT_FAILURE);
  }

  while (fgets(buffer, BUFFER, logfile) != NULL)
  {
    printf("%s", buffer);
  }

  printf("\n");
  fclose(logfile);

  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM