In essence I have come across an issue while working on a project to send files over a socket. I'm a bit of a newbie, and after a few hours of searching I still haven't found a working solution, but I have boiled down the problem into the following code.
#include <stdio.h>
#include <errno.h>
#include <Windows.h>
int main()
{
const char* fileName = "C:\\Users\\Username\\Desktop\\bugs.jpg";
FILE* f;
fopen_s(&f, fileName, "r");
if (f == NULL)
printf("Null Result");
else
printf("Working");
printf("\nError %d \n", errno);
}
For some reason the program is unable to open the file, and errno returns a value of 22, which corresponds to EINVAL, or invalid argument here. I am very confused as it appears that I am providing fopen_s with the correct arguments according to its specification. Any help or pointers(haha) is greatly appriciated, thanks!
Thanks to the comments I found out why it wasn't working. Essentially, I was copying the "Object Name" field from the file properties to save time typing it out. Somehow this drags along an invisible '\u202A' character which completely breaks fopen_s.
Picture
In a nutshell, don't try and cut corners.
Related
Just to make it clear - I'm a beginner in C.
When my program is running (using Xcode), no values correspond to the values in "resultfortran.txt". Instead, they become very small, very large or zero (looks random). For example, the variable n becomes 0, even though the first line in "resultfortran.txt" is 10. The variables min and max also becomes very small (and don't get the values at line 2 and 3).
I have searched the web all day, and asked my fellow students. If it is of interest, I got the error "EXC_BAD_ACCESS" on the line where the file is opened, but that error has (some how?) disappeared. And yes, "resultfortran.txt2 is in the same folder as main.m.
The start of the program is shown below:
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <GLUT/glut.h>
#include <OpenGL/OpenGL.h>
#include <Cocoa/Cocoa.h>
static void draw( void )
{
int n,i,j;
float step,min,max,x,y,scaled;
float matrix[1000][1000];
FILE *fp; //reads input file
fp=fopen("resultfortran.txt", "r");
fscanf(fp,"%d",&n); //Gives n the value of the first line.
step=(1.0/n); //Defines step size
fscanf(fp,"%f",&min); //Gives min the value of the second line.
fscanf(fp,"%f",&max); //Gives max the value of the third line.
for (i=0;i<n+1;i=i+1)
{
for (j=0;j<n+1;j=j+1)
{
fscanf(fp,"%f",&matrix[i][j]);
}
}
... not finished here ...
The first lines of the file "resultfortran.txt" (which is a output from a fortran script) is shown below:
10
0.00000000
0.500000000
0.0000000000
0.0025000002
0.0100000007
0.0225000009
0.0400000028
0.0625000000
0.0900000036
0.1224999949
0.1600000113
0.2024999857
0.2500000000
0.0025000002
0.0050000008
0.0125000002
Since you're "a beginner in C", I want to first welcome you to what is a very rigorous but rewarding language. Though, to be fair, I wouldn't consider someone who is writing operating system code to be a "beginner" in C.
I'll gladly assist you and update this answer as we proceed. My first suggestion is as follows:
The first thing you always should do when doing file operations (like opening one) is to check the results of the execution! For example, if you read the man page on fopen(), you'll see that fopen() will
return a FILE pointer. Otherwise, NULL is returned and errno is set to
indicate the error.
So, use something similar to the code below to make sure that your file is opening as expected:
if (fp == NULL) {
printf("fopen did not work! Check errno %d\n", errno);
}
else {
printf("fopen workd!\n");
}
I will update this answer once you get back to me on the results of implementing the code above.
I'm actually having problems with not one but 2 to 3 programs using files and their commands like fopen, fscanf, while(strcmp(input,"E")!=0).Atleast, I think that is the problem. All these programs show the same error that is debug assertion failed! Expression (stream!=null).I tried everything but nothing seems to work pls help. I cant understand what to do. Pls reply as soon as possible.This is one of the programs:
# include <stdio.h>
# include <conio.h>
# include <string.h>
# include <stdlib.h>
void main()
{ char add[6],length[10],input[10],binary[12],bitmask[12],relocbit;
int start,inp,len,i,address,opcode,addr,actualadd;
FILE *fp1=fopen("relinput.dat","r");
FILE *fp2=fopen("reloutput.dat","w");
system("cls");
printf("Enter the actual starting address : ");
scanf("%d",&start);
fscanf(fp1,"%s",input);
while(strcmp(input,"E")!=0)
{ if(strcmp(input,"H")==0)
{ fscanf(fp1,"%s",add);
fscanf(fp1,"%s",length);
fscanf(fp1,"%s",input);
}
if(strcmp(input,"T")==0)
{ fscanf(fp1,"%d",&address);
fscanf(fp1,"%s",bitmask);
address+=start;
len=strlen(bitmask);
for(i=0;i<len;i++)
{ fscanf(fp1,"%d",&opcode);
fscanf(fp1,"%d",&addr);
relocbit=bitmask[i];
if(relocbit=='0')
actualadd=addr;
else
actualadd=addr+start;
fprintf(fp2,"%d\t%d%d\n",address,opcode,actualadd);
address+=3;
}
fscanf(fp1,"%s",input);
}
}
fclose(fp1);
fclose(fp2);
printf("FINISHED");
getch();
}
You need to do error checking on your fopen procedures and in general. This error is most likely due to a fscanf or fopen returning an unexpected value that you didn't catch.
More useful tips:
Debug with breakpoints if your IDE allows you to
Format your code to be more in line and easily readable
Comment on Functions to make clear what they do, for future readers or your future self.
There are probably several problems with the code below. Found it online after searching for a way to get keyboard input in linux. I've verified the correct event for keyboard input. The reason it seems fishy to me is regardless of what i put in the filepath, it always seems to pass the error check (the open call returns something greater than 0). Something is obviously wrong, so suggestions are welcome.
This won't run correctly unless you run the exe as su.
When i want to read in my keystroke, do i just use something like fgets on the file descriptor in an infinite while loop(would that even work)? I want it to be constantly polling for keyboard inputs. Any tips on decoding the inputs from the keyboard event?
Thanks again! This project of mine may be overly ambitious, as it's been a really long time since i've done any coding.
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <fcntl.h>
#include <linux/input.h>
#include <unistd.h>
// Edit this line to reflect your filepath
#define FILE_PATH "/dev/input/event4"
int main()
{
printf("Starting KeyEvent Module\n");
size_t file; //will change this to int file; to make it possible to be negative
const char *str = FILE_PATH;
printf("File Path: %s\n", str);
error check here
if((file = open(str, O_RDONLY)) < 0)
{
printf("ERROR:File can not open\n");
exit(0);
}
struct input_event event[64];
size_t reader;
reader = read(file, event, sizeof(struct input_event) * 64);
printf("DO NOT COME HERE...\n");
close(file);
return 0;
}
the problem is here:
size_t file;
size_t is unsigned, so it will always be >=0
it should have been:
int file;
the open call returns something greater than 0
open returns int, but you put in in an unsigned variable (size_t is usually unsigned), so you fail to detect when it is <0
My first post :), am starting out with C language as basic learning step into programming arena. I am using following code which reads string from text file, makes directory with that string name and opens a file for writing in that created directory. But am not able to create a file inside directory made, here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <string.h>
int main()
{
char file_name[25], cwd[100];
FILE *fp, *op;
fp = fopen("myfile.txt", "r");
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
fgets(file_name, 25, fp);
_mkdir(file_name);
if (_getcwd(cwd,sizeof(cwd)) != 0)
{
fprintf(stdout, "Your dir name: %s\\%s\n", cwd,file_name);
op = fopen("cwd\\file_name\\mynewfile.txt","w");
fclose(op);
}
fclose(fp);
return 0;
}
What you need is to store the file name (with the path) in a c-string before opening. What you are opening is cwd\file_name\mynewfile.txt. I doubt that your directory is named cwd.
A sample could could be:
char file_path[150];
sprintf(file_path, "%s\\%s\\mynewfile.txt", cwd, file_name);
op = fopen(file_path,"w");
use
#include <sys/stat.h>
#include <sys/types.h>
instead of
#include <direct.h>
and modify
op = fopen("cwd\\file_name\\mynewfile.txt","w”);
I see you are using the return values. That is a good start for a beginner. You can refine your error messages by including "errno.h". Instead of printing your own error messages call
printf("%s", strerror(errno));
You get more precise error messages that way.
op = fopen("cwd\\file_name\\mynewfile.txt","w”);
You’re actually passing the string literals “cwd” and “file_name” as part of the path of the file, when I think you actually mean to put the contents of the variables with those names in there. You will probably have to piece together a string for the path. Try looking into strcat()
http://www.cplusplus.com/reference/cstring/strcat/
The program always ends up exiting. I seem to be running in to this problem frequently and I think I somehow previously fixed it but I'm not sure how. Why does it not create a file?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (void){
FILE *fp;
int c;
char file_w[100];
char string[100];
printf("Enter filename\n");
fgets(file_w, 100, stdin);
fp = fopen(file_w, "w");
if (fp == NULL){
printf("Can't open file\n");
exit(0);
}
printf("Enter a string");
fgets(string, 100, stdin);
for(c = 0; c <= sizeof(string); c++)
{
fprintf(fp, "%s\n", string);
}
printf("file written");
fclose(fp);
return 0;
}
Try to print the name of the file you have entered:
printf("%s\n", file_w);
just after the line you get file_w, just to be sure to enter what you want. I same cases the terminal could be wrongly configured.
Try to enter an absolute name path, if your computer is a Linux or Unix:
/tmp/newfile.txt
If your computer is Windows... Well try to see if C:\temp\ exist (or create it) and then enter:
C:\temp\newfile.txt
In any case, remember that you can specify an absolute path, and not only the file name. So double check if you have the rights (i.e. the permissions) to write into the directory where the file should be written.
In case you want check the error and have a better description of the problem try to use the following lines instead of your code, just under the fopen
if( fp == NULL ) {
// Error, as expected.
perror( "Error opening file" );
printf( "Error code opening file: %d\n", errno );
printf( "Error opening file: %s\n", strerror( errno ) );
exit(-1);
}
strerror it is a wonderful function just because return you a description of the problem instead of an error code.
I bet the problem is "invisible character after actual name from fgets()". I'll let you figure out exactly what that character is, where it comes from and how to fix it, as "struggling to solve a problem" is part of the learning process when it comes to programming. If it was easy, everyone could do it.
If the return value of fopen is NULL it means some error occurred. I suggest you look into the errno global to see what error has occurred to help you debug why it's not opening the file.
The w flag does the following:
write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
So it should create a file when none exists, or when it does exist, overwrite its content.
If it does not do that, you have another problem, but from the little information you've given, it's hard to tell what it is.
I tried as a name of file the following:
C:\\temp\\test_file.txt
or
fopen("C:\\temp\\employees.txt", "w");
and it works fine, without errors (I made it in Windows 10. GCC win32, Version: 6.3.0).
I think that you have to use an absolute path to create the file.
use gets() instead of fgets()...it will work
.
.
gets(file_w);
.
.