I have a big program that is causing me access violation when using sdl_rwops. So I decided to create a small program just to test sdl_rwops and it is causing me the same access violation. For what I could see it is being caused because of the fopen_s() part but I could not figure out why.
Maybe you guys can find what I am missing.
Here is the code:
#include "SDL.h"
#include < stdio.h >
int main(int argc, char *argv[])
{
FILE *file;
SDL_Surface *screen;
SDL_Surface *one;
SDL_Rect rect;
errno_t err;
/* This is the RWops structure we'll be using */
SDL_RWops *rw;
SDL_Init(SDL_INIT_VIDEO);
atexit(SDL_Quit);
screen = SDL_SetVideoMode(640, 480, 16, SDL_DOUBLEBUF);
/* Here we get a file pointer to a bitmap */
if ( (err = fopen_s(&file,"penguin.bmp", "r")) != 0)
{
printf("Couldn't load penguin.bmp\n");
exit(1);
}
/* This is where we actually create our RWops structure. Here we're
instructing SDL to get it from the file pointer we just opened */
rw = SDL_RWFromFP(file, 0);
/* SDL_LoadBMP_RW is the RWops version of the old standby,
SDL_LoadBMP. This will get the image from the RWops you passed
in; in this case the file you've opened */
one = SDL_LoadBMP_RW(rw, 0); // This line calls fopen.c and causes the crash
/* Clean up after ourselves */
SDL_FreeRW(rw);
fclose(file);
/* Haphazard way of getting stuff to the screen */
rect.x = rect.y = 20;
rect.w = one -> w;
rect.y = one -> h;
SDL_BlitSurface(one, NULL, screen, &rect);
SDL_Flip(screen);
SDL_Delay(3000);
}
And here is the portion of fopen.c that causes the crash of the program:
errno_t __cdecl _tfopen_s (
FILE ** pfile,
const _TSCHAR *file,
const _TSCHAR *mode)
{
_VALIDATE_RETURN_ERRCODE((pfile != NULL), EINVAL);
*pfile = _tfsopen(file, mode, _SH_SECURE); // This line causes the access violation
if(*pfile != NULL)
return 0;
return errno;
}
The line
one = SDL_LoadBMP_RW(rw, 0);
jumps to fopen.c and the line
*pfile = _tfsopen(file, mode, _SH_SECURE);
in that file makes it crash.
I am using Visual Studio 2012 and the picture is in the same folder as the executable. The SDL.dll and even SDL_image.dll are there too.
I found a post in google of the same issue and the person said that when he put the whole path (instead of just penguin.bmp") it would not crash. It did not work for me, crashed anyway.
I am starting to think that it may be some SDL initialization issue but I did anything I could find on google and nothing worked. I tryed running in Multi-threaded DLL (/Md), in Multi-threaded Debug Dll (/MDd), tryed running in 64 bits, tyred changing the Subsystem to Windows and to console... everything resulted in the same crash.
If you read the documentation of SDL_RWFromFP
Description
SDL_RWFromFP creates a new SDL_RWops structure from a file pointer, opened with stdio. If autoclose is nonzero, the file will be automatically closed when the RWops structure is closed.
Note: This is not available under Win32, since files opened in an application on that platform cannot be used by a dynamically linked library.
Note: This function is not present in SDL-1.2-svn4446
So you need to use SDL_RWFromFile if you want to use RWOps.
Also SDL 2 has many improvements over SDL 1.* and I would highly recommend switching to that.
Related
I have a program that reads a file, returned from an OPENFILENAME. It has a large edit control. That is supposed to get the text from the file and let the user save it. I just cannot wrap my head around it. fopen(path, "r+") throws an exception for some odd reason.
Exact error message:
"Exception thrown at 0x00007FF87B5A86E2 (ucrtbased.dll) in Notepad (C).exe: 0xC0000005: Access violation reading location 0x000000000000722B."
Here is the function reading it:
void ReadOpenedFile(char* path, HWND hTextBox)
{
// Warning suppressor because it doesn't build without fopen_s it seems.
#pragma warning (disable: 4996)
FILE* f = fopen(path, 'r+');
SetWindowText(hTextBox, f);
fclose(f);
}
I had gotten it from the documents folder, but I knew because Windows protects it, I tried the music folder. It still didn't work. I tried many different websites. They all said the same approach to open files. I always get the same exception. I had tested the OPENFILENAME was returning the correct file path, and it does.
Any help is appreciated!
You never read the file but only open it. It should be (beware untested):
void ReadOpenedFile(char* path, HWND hTextBox)
{
// Warning suppressor because it doesn't build without fopen_s it seems.
#pragma warning (disable: 4996)
FILE* f = fopen(path, "rt");
// error test for f == NULL omitted for brievety
char buf[16384]; // adjust per you requirement up to ~32000
size_t sz = fread(buf, 1, sizeof(buf) - 1, f);
buf[sz] = '\0';
SetWindowTextA(hTextBox, buf);
fclose(f);
}
I'm trying to write to an existing bmp file.
the action should delete the data on it, which is fine by me.
first i want to read the original header, then switch the width and the height data and then "create" new file with the new header.
for some reason, i managed to open and read the file in "rb" mode, but when i try to do so in "wb" mode or any other mode for writing, the file pointer is initialized as NULL.
reading with struct BmpHeader works just fine.
Update:
after using:
err = fopens(...);
i got that err = 13.
how can i fix this?
#define HEADERSIZE 54
int **Matrix = GivenMatrix;
FILE *f;
int row, col,i;
BmpHeader header;
long Newwidth, Newheight;
int pixelBytesInRow, padding;
fopen_s(&f, "plate.bmp", "rb");
fread(&header, HEADERSIZE, 1, f);
fclose(f);
Newheight = header.width;
Newwidth = header.height;
header.width = Newwidth;
header.height = Newheight;
fopen_s(&f, "plate.bmp", "wb");
fwrite(&header, HEADERSIZE, 1, f);
fopen_s() returns a non-zero error code and sets the file handle to null and the global value errno to the appropriate error code when an error occurs. To see what happened, use perror() to print the error message:
if (fopen_s(&f, "plate.bmp", "wb") != 0) {
perror("could not open plate.bmp");
// Exit or return.
}
perror() will append the system's error to your own message, with a : before it.
Also do the same when opening the file for reading. Never assume that file operations are going to succeed. You really, really need to do error handling when doing any kind of I/O.
If the error is "permission denied", then that usually means the file is open elsewhere. Either in your own program, or by an external program (like an image viewer you're using to check the bmp file.) Close it. On Windows, you can't open files in write mode if they are open elsewhere too.
If you want to avoid situations where you forgot to close files, you should use RAII facilities in C++. It's arguably the most important and useful part of C++. In this case, you could either switch to C++ streams, or if you want to continue using the cstdio API, then wrap your file handles in your own type that automatically closes the handle when it goes out of scope (either in the destructor, or by using a unique_ptr with a the custom deleter set to fclose.)
just installed eclipse on my linux and trying working with files.
I wanted to use fgetc function but it seems that its not working..
while debugging: even if Im using step over its crush, and while letting it run its just dont do anything.
its happen also for every function related to files like fscanf,fgets etc..
the error messege is:
Can't find a source file at "/build/glibc-OTsEL5/glibc-2.27/libio/getc.c"
Locate the file or edit the source lookup path to include its location.
any ideas?
thnk's in advanced
and this is my code:
#include <stdio.h>
#include <stdlib.h>
int main(){
func();
return 0;
}
void func(){
int ch;
int fd = open("out.txt", O_RDONLY);
if(fd < 0)
perror("fd");
ch = fgetc(fd);
printf("%d",ch);
}
The error message comes from the debugger. It indicates that whoever built glibc for your system did not add source files to the debugging information. As a result, stepping through system library functions such as fgetc is very confusing. But this is independent of your actual problem.
You cannot mix file descriptor functions like open with file stream functions like fgetc. The compiler will have print a type mismatch warning; you really should not ignore these.
Something like this should fix the type error:
File *fp = fopen("out.txt", "r");
if (fp == NULL) {
perror("fopen");
return 1;
}
ch = fgetc(fp);
If you want to keep using unbuffered I/O and open, you will have to use the read function instead of fgetc to read bytes.
What I am trying to do is create a program that will, while running, open examplecliprogram.exe with "--exampleparameter --exampleparameter2" as cli input, wait for examplecliprogram.exe to terminate, and then take the output and do something useful with it. I would like examplecliprogram.exe to run in the background (instead of being opened in another window) while the output from examplecliprogram.exe is displayed in the window running the overhead program.
So far I've explored options such as popen(), ShellExecute(), and CreateProcess() but I can't seem to get any of them working properly.
Primarily, I want this program to be able to run independently in a Windows environment, and compatibility with Linux would be a bonus.
edit: I have found one solution by calling system("arguments"). I don't know if this is a good solution that will transfer well to a gui, but at the very least it solves the fundamental problem.
This code runs on Windows and Unix (I tested in Visual Studio, GCC on Cygwin, and GCC on Mac OS X).
I had to use a macro to define popen depending on the platform, because on Windows, the function is _popen, while on other platforms the function name is popen (note the underscore in the former).
#include <stdlib.h>
#include <stdio.h>
/* Change to whichever program you want */
//#define PROGRAM "program.exe --param1 --param2"
#define PROGRAM "dir"
#define CHUNK_LEN 1024
#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#endif
int main(int argc, char **argv) {
/* Ensure that output of command does interfere with stdout */
fflush(stdin);
FILE *cmd_file = (FILE *) popen(PROGRAM, "r");
if (!cmd_file) {
printf("Error calling popen\n");
}
char *buf = (char *) malloc(CHUNK_LEN);
long cmd_output_len = 0;
int bytes_read = 0;
do {
bytes_read = fread(buf + cmd_output_len, sizeof(char), CHUNK_LEN, cmd_file);
cmd_output_len += bytes_read;
buf = (char *) realloc(buf, cmd_output_len + CHUNK_LEN);
} while (bytes_read == CHUNK_LEN);
/* Nul terminate string */
*((char *) buf + cmd_output_len) = '\0';
/* Close file pointer */
pclose(cmd_file);
/* Do stuff with buffer */
printf("%s\n", buf);
/* Free buffer */
free(buf);
return 0;
}
You may want to have a look to this Microsoft example code. It was useful to me.
http://msdn.microsoft.com/en-us/library/ms682499%28VS.85%29.aspx
I used CreateProcess, unfortunately I can't recommend you anything other than 'carefull reading of msdn' and 'starting from simple and progress to complex'.
As for the portability - if you havent need to use some cross-platform toolkit until now, i wouldnt recommend you to start to use one just because of this. I would recommend you to write some 'start process' wrapper and implement it on each platform by its native way.
The cleanest and most portable way of doing this is to use GLib's g_spawn_sync().
You can find the docs online.
gchar * std_out = NULL;
gchar * std_err = NULL;
gint exit_stat = 0;
const char *argv[] = {"--foo", "123", "--bar", "22323", NULL};
if(!g_spawn_sync (NULL, argv, NULL, NULL, NULL, NULL, &std_out, &std_err, &exit_stat, NULL)){
fprintf(stderr, "Failed to spawn!\n");
};
/* std_out and std_err should now point to the respective output.*/
We are working on a homework on CELL programming for college and their feedback response to our questions is kinda slow, thought i can get some faster answers here.
I have a PPU side code which tries to open a file passed down through char* argv[], however this doesn't work it cannot make the assignment of the pointer, i get a NULL.
Now my first idea was that the file isn't in the correct directory and i copied in every possible and logical place, my second idea is that maybe the PPU wants this pointer in its LS area, but i can't deduce if that's the bug or not. So...
My question is what am i doing wrong?
I am working with a Fedora 7 SDK Cell, with Eclipse as an IDE. Maybe my argument setup is wrong tho he gets the name of the file correctly.
Code on request:
images_t *read_bin_data(char *name)
{
FILE *file;
images_t *img;
uint32_t *buffer;
uint8_t buf;
unsigned long fileLen;
unsigned long i;
//Open file
file = (FILE*)malloc(sizeof(FILE));
file = fopen(name, "rb");
printf("[Debug]Opening file %s\n",name);
if (!file)
{
fprintf(stderr, "Unable to open file %s", name);
return NULL;
}
//.......
}
Main launch:
int main(int argc,char* argv[]) {
int i,img_width;
int modif_this[4] __attribute__ ((aligned(16))) = {1,2,3,4};
images_t *faces, *nonfaces;
spe_context_ptr_t ctxs[SPU_THREADS];
pthread_t threads[SPU_THREADS];
thread_arg_t arg[SPU_THREADS];
//intializare img_width
img_width = atoi(argv[1]);
printf("[Debug]Img size is %i\n",img_width);
faces = read_bin_data(argv[3]);
//.......
}
Thanks for the help.
I got it, if anyone else had issues with it you have to enable the upload rules and upload the extra-files you desired to be used by the simulator. :)
Exactly which line is failing, and how?
You should look at errno to see what error is being returned from fopen or other calls.
Also, it should not cause this problem, but you don't need the line:
file = (FILE*)malloc(sizeof(FILE));
That memory will just be leaked...