Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This error occurred in my program:
Debug Assertion Failed!
Program:C:\JM\.\bin\ldecod.exe
File: f:\ff\vctools\crt_bld\self_x86\crt\src\fscanf.c
Line:52
Expression: (stream!=NULL)
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application.)
What seems to be the problem here?
CODE
This is the portion of my code where I used fscanf. When mi=297 it worked perfectly fine.
int myframe[29699];
........
if (CONCEAL==1)
{
FILE*concealfile;
concealfile=fopen("myerrsim%15carphone.txt","r");
for(mi=0; mi<14850; mi++)
{
fscanf(concealfile,"%d\n", &myframe[mi]);
}
if (myctr==currMB->mbAddrX+(((currMB)->p_Slice)->p_Img)->number*99 && currMB->mbAddrX+(((currMB)->p_Slice)->p_Img)->number>0)
{
if (myframe[myctr]==1)
{
mbmode=0;
}
myctr++;
}
}
Additional questions! I am encountering several similar errors. The
programs breaks at different portions of source codes and some of
which are built in functions like "fscanf". I do not know the reason.
And sometimes a program on my computer, like "Flash Player" notifies
me of some sort of error. Is this because the pointers used in my
program are trying to access "Flash Player"? Why is this happening and
what is the possible fix?
What are assertion errors simply put?
For #Jonathan Leffler
#ifdef _DEBUG
/*
* Report error.
*
* If _CRT_ERROR has _CRTDBG_REPORT_WNDW on, and user chooses
* "Retry", call the debugger.
*
* Otherwise, continue execution.
*
*/
if (rterrnum != _RT_CRNL && rterrnum != _RT_BANNER && rterrnum != _RT_CRT_NOTINIT)
{
switch (_CrtDbgReportW(_CRT_ERROR, NULL, 0, NULL, L"%s", error_text))
{
-> case 1: _CrtDbgBreak(); msgshown = 1; break;
case 0: msgshown = 1; break;
}
}
where -> is the unexpected breakpoint.
located in C:\Program Files\Microsoft Visual Studio 11.0\VC\crt\src\crt0msg.c
It appears you did something like:
char name[64];
FILE *fp = fopen("c:/non-existent/file", "r");
fscanf(fp, "%s", name);
without checking that fopen() was successful, and fprintf() triggered an assertion failure. When fopen() fails, it returns a NULL pointer, and the assertion says stream != NULL (where 'stream' is a file stream, the first argument to fscanf(), and means aFILE *such asfp`).
There's an outside chance that you use fscanf_s() because you're on Windows — it's the same basic story, but fscanf_s() checks for such problems where fscanf() does not.
Possible fix:
char name[64];
FILE *fp = fopen("c:/non-existent/file", "r");
if (fp == 0)
...report failure to open file (and exit or return)...
if (fscanf(fp, "%s", name) != 1)
...report read failure...
Related
This question already has answers here:
Why does printf not flush after the call unless a newline is in the format string?
(10 answers)
Closed 5 years ago.
I have the following snippet of code at the beginning of my program:
printf("Starting extraction of file %s \n", tarName);
// Open the tarFile
FILE* tarFile = fopen(tarName, "r");
if(tarFile == NULL) return EXIT_FAILURE;
// Read nFiles
printf("Reading header...");
...
When I execute it from the terminal I get the following output:
Starting extraction of file test.mytar
And then the program freezes, apparently never reaching the second printf.
test.mytar is an existing file in the same folder as my executable, and this is the same folder from where I am executing the terminal.
The file was created by me byte a byte, so it could possibly be violating file conventions I am not aware of.
What could possibly be going on here?
As pointed out in the comments, two things may happen.
a) the fopen fails (IO error, permission denied, missing file, ...). To know the exact cause, you need to print the errno (or GetLastError() on Windows) :
if(tarFile == NULL) {
printf("%s\n", strerror(errno));
return EXIT_FAILURE;
}
b) the fopen succeeds but printf("Reading header..."); does not show up anything because the message is buffered and not yet printed. To correct this, you can generally add a '\n' at the end of the message.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm writing a program which counts how many times each C keyword is contained in an ASCII file selected by the user. So I use scanf to save the name that the user selected as filename and check with fopen if a file with that name exists in the same dir as the C program. The problem lies in the fact that if the filename selected by the user contains spaces fopen gives an error because it can't find such a file. So here's the question, how do I open a file with fopen that contains spaces in the name of it? Here is the code that i used for the program
selectfilename(filein,1) ;
if (fopen(filein,"r") == NULL){
perror("Error ") ;
return (1) ;
}
void selectfilename(char *cp, int num){
if (num == 1) printf("Please select the name of the file to be opened including the extension : ") ;
else printf("Please select the name of the file to save the statistics including the extension : ") ;
scanf("%s",cp++) ;
}
I think your problem is with scanf, not fopen – which handles filenames with spaces just fine.
scanf("%s") only parse until the first space. It's hard to propose a fix without seeing more of the code.
Update:
Since you read from stdin you can try this to read until the line terminator.
char buf[256];
int rv = scanf ("%255[^\n]", buf); // 255 is max chars to read
if (rv == 0 || rv == EOF)
buf[0] = 0;
printf ("[%s]\n", buf);
Update 2: Fixed bugs reported by #chux
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm putting some very temporary debug prints into various userspace programs to figure out what code runs on an embedded Linux device, and I want these prints to write to a file without leaving it open. To make the debug more portable between the various programs, it would be nice to have a one-liner that can open a file, write to it, and close it without having to define a function/macro elsewhere. I could do something like:
{ FILE *f = fopen("filename", "a"); if (f) { fprintf(f, "DEBUG MSG\n"); fclose(f); } else printf("File open error!\n"); }
which is just removing the whitespace from:
{
FILE *f = fopen("filename", "a");
if (f) {
fprintf(f, "DEBUG MSG\n");
fclose(f);
}
else
printf("File open error!\n");
}
But this feels needlessly complex. Is there some more simplified way of doing this? Again, I'm not talking about making it a function, as I'd like it to be copy/pasted between separate programs without defining a function every time. It's just basically a temporary printk equivalent for userspace.
Functions.
Extra chars for my shortest answer.
Potential problem with fprintf(f, "DEBUG MSG\n");
I assume "DEBUG MSG\n" is some placeholder for the true message. Should the true message contain a '%', then the function will look for missing arguments. Use fputs() - its can be lighter on the CPU too than fprintf().
fputs(debug_message, f);
The true message may lack a '\n' and then get stuck in buffering just prior to a program crash. Best to flush when you are done.
fputs(debug_message, f);
fflush(f);
Pedantic: Debugging is for problem solving. Too often the message itself is questionable/corrupt. Consider using protection. (I do not trust excessive long debug messages). Of course the more junk in the fprintf(), the greater the performance impact of debug logging.
if (f) {
if (debug_message) {
fprintf(f, "%.99s", debug_message);
fflush(f);
fclose(f);
}
}
As mentioned by #Tom Karzes, send diagnostic message to stderr, rather than stdout.
Overall, I would use a function call wrapped in a conditional macro rather than embedded code. YMMV.
#ifdef NDEBUG
#define DEBUG_PUTS(level, s)
#else
#define DEBUG_PUTS(level, s) debug_puts((level), __FILE__, __LINE__, (s))
#endif
As mentioned by Mark Plotnick, a workaround for Linux systems is:
system("echo DEBUG MSG >> filename");
It's not pretty but it's quick, copy/pasteable, and easy to use for this situation because it can also write to /dev/kmsg:
system("echo DEBUG MSG >> /dev/kmsg");
which allows it to behave like a printk. Of course, it's not a safe solution and can't be used with any chars that interfere with a bash echo, but for a temporary static debug message it works fine.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Is there a preferable way to report errors in C? For example if a file that is supposed to be opened does not exist, should I use
if( fp == NULL )
{
perror("Error: ");
return(-1);
}
(copied from http://www.tutorialspoint.com/c_standard_library/c_function_perror.htm )
or
if( fp == NULL )
{
fprintf(stderr, "Unable to open file for reading.\n");
return(-1);
}
You can use perror() or strerror to get the error message. If you want to postpone the display of error message or if you want to log the message to a file, then save the errno and use strerror() because perror only writes to the standard error stream and it uses the global errno set and the errno might change any time if any library function is called before printing the error message.
Example using saved errno:
int savederrno;
....
if( fp == NULL )
{
savederrno = errno; /* Save the errno immediately after an api/lib function or a system call */
/*If you want to write to a log file now, write here using strerror and other library calls */
}
....
/* use strerror function to get the error message and write to log
or write to std error etc*/
The following man pages explain the error reporting in detail.
http://www.gnu.org/software/libc/manual/html_node/Error-Messages.html
http://man7.org/linux/man-pages/man3/errno.3.html
tutorialspoint.com is extremely terrible (at least when it comes to C) and as such must not be used. The standard resource to learn from is "The C Programming Language, 2nd edition" by Kernighan and Ritchie.
The preferred way to report stuff is to include the failing function in the message and use perror, e.g. perror("open")
EDIT: originally this did not include any justification for the claim about the site. I did not feel like it is necessary nor sensible. There is no write up I could link to either. They key was to avoid the site and everyone interested can easily conclude material in there is questionable at best and straight up wrong at worst.
However, since I got a weird backlash here are some excerpts:
http://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm
#include <stdio.h>
#include <stdlib.h>
Missing include for strcpy and strcat.
int main()
{
char *str;
/* Initial memory allocation */
str = (char *) malloc(15);
No need to cast malloc. Missing null-check. Why the 15?
strcpy(str, "tutorialspoint");
Bad error-inducing style. What if the length was to change? If an explicit allocation really needs to happen, strlen() + 1 can be used to get the needed size.
printf("String = %s, Address = %u\n", str, str);
'u' is an incorrect specifier for pointer type.
/* Reallocating memory */
str = (char *) realloc(str, 25);
Standard bad idiom. The code should use a temporary pointer to recover from error, or if recovery is not an option, exit.
strcat(str, ".com");
What's up with realloc from 15 to 25 just to add ".com"?
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}
Does this justify my claim about the site?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
#include <stdio.h>
//Just a program that writes data (in our case 3 integers) in a file with the name GRADES.
int main(void)
{
int a=5,b=6,c=7; //var declaration.
FILE *point; //Creating a pointer to work with a file.
point = fopen("GRADES","w"); //we point the location to the memory where we wanna input data (in this case GRADES.c).
fprintf(point,"%d\n %d\n %d",a,b,c); //calling function fprintf to load the data in the GRADES file.
fclose(point);// Closing the file (optional) c usually close it without telling.
return 0;
}
// i use the free open source platform CODE:BLOCKS
By checking for errors you should be able to tell exactly what your problem is.
fopen
fopen will return NULL if it fails:
point = fopen("GRADES","w");
if(!point)
{
fprintf(stderr, "Failed to open file!\n");
return -1;
}
fprintf
fprintf will return how many bytes written. If it fails, a negative number is returned:
int num = fprintf(point,"%d\n %d\n %d",a,b,c);
if(num < 0)
{
fprintf(stderr, "Write error!\n");
return -1;
}
fclose
fclose will return EOF on error:
int status = fclose(point);
if(status == EOF)
{
fprintf(stderr, "Failed to close file!\n");
return -1;
}