C File handling in visual studio 2017 - c

The file handling commands in Visual Studio seem to be different than normal. I'm currently learning the very basics of File Handling in C, but the commands don't seem to be working. This is what I've got right now -
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\", "program.txt", "w");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf_s("%d", &num);
fprintf(fptr, "%d", num);
fclose(fptr);
return 0;
}
Here's the build output-
'fopen': too many actual parameters
warning C4013: 'exit' undefined; assuming extern returning int
error C4996: 'fopen': This function or variable may be unsafe. Consider using
fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
When I use fopen_s instead, like this fopen_s("C:\program.txt", "w"), it says-
'function': 'FILE **' differs in levels of indirection from 'char [15]'
'fopen_s': different types for formal and actual parameter 1
'fopen_s': too few arguments for call
'=': 'FILE *' differs in levels of indirection from 'errno_t'
I need some serious help.

You should open your file with either
FILE * f;
f= fopen("C:\\program.txt", "w");
or
FILE * f;
int err = fopen_s(&f, "C:\\program.txt", "w");
the latter takes FILE ** as an extra argument, and return error code (0 on success).

There is a extra comma , in fopen() which makes fopen() as three arguments, which is wrong & causing the error
'fopen': too many actual parameters
This
fptr = fopen("C:\\", "program.txt", "w"); /* fopen() expects 2 arguments */
replaces with
fptr = fopen("C:\\program.txt", "w");
You can disable below
'fopen': This function or variable may be unsafe. Consider using
fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
warning by
#pragma warning(disable:4996) /* use it before other headers */
Or use fopen_s().

Related

Multiple definition of `main' while bison output file compiling

So I'm writing a bison (without lex) parser and now I want to read the input code from file and to write the output to another file.
Searching the stackoverflow for some time I found that this way should be good.
bison.y:
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern FILE *yyin;
int yylex() { return getc(stdin); }
void yyerror(char *s) {
fprintf (stderr, "%s\n", s);
}
int counter = 1;
char filename2[10] = "dest.ll";
FILE *f2;
%}
%name parse
%%
//grammars
%%
int main(int argc, char *argv[]) {
yyin = fopen(argv[1], "r");
if (argc > 2)
f2 = fopen(argv[2], "w");
else
f2 = fopen(filename2, "w");
yyparse();
return 0;
}
Then i compile it this way:
bison bison.y
cc -ly bison.tab.c
And here the result of cc-compilation:
/tmp/ccNqiuhW.o: In function `main':
bison.tab.c:(.text+0x960): multiple definition of `main'
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/liby.a(main.o):(.text.startup+0x0): first defined here
/tmp/ccNqiuhW.o: In function `main':
bison.tab.c:(.text+0x98c): undefined reference to `yyin'
collect2: error: ld returned 1 exit status
The output bison.tab.c file have only 1 main. Ofc int/void main doesn't matter. Can you teach me how to do it correctly?
P.S. By the way, I don't want to spam different posts, and have a little question here. How can I store the string (char *) in $$ in bison? For example, I want to generate a code string after I met the int grammar. I have this error and can't find the answer:
bison.y:94:8: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
INTNUM: NUMBER | DIGIT INTNUM {$$ = "string"};
bison.y: In function ‘yyparse’:
bison.y:28:15: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
PROGRAM: EXPRS { fprintf(f2, "%s: string here %d.\n", $$, counter++) };
will be extremely good if I find the help.
You are linking library liby (linker option -ly). The Bison manual has this to say about it:
The Yacc library contains default implementations of the yyerror and
main functions.
So that's why you have multiple definitions of main. You provide one, and there's one in liby.
Moreover, the docs go on to say that
These default implementations are normally not useful, but POSIX requires them.
(Emphasis added)
You do not need to link liby in order to build a program that includes a bison-generated parser, and normally you should not do so. Instead, provide your own main() and your own yyerror(), both of which you've already done.
Additionally, you are expected to provide a definition of yyin, not just a declaration, whether you link liby or not. To do so, remove the extern keyword from the declaration of yyin in your grammar file.
Your grammar is not complete (there are no rules at all) and the %name directive is not documented and is not recognized by my Bison, but if I add a dummy rule and comment out the %name, in conjunction with the other changes discussed, then bison generates a C source file for me that can be successfully compiled to an executable (without liby).

input redirection on CMD

Well, I am learning programming in C, and I got an assignment to get 3 characters from an input text file into 3 variables and then print their ASCII values.
I wrote this code:
#include <stdio.h>
int main()
{
char a,b,c;
printf("Insert 3 characters:\n");
a=getch();
b=getch();
c=getch();
printf("%d, %d, %d",(int)a,(int)b,(int)c);
}
I opened a text file (input.txt) and wrote there: "abc".
I managed to compile the code with the MinGW compiler, and on the CMD window that I opened in the folder of the .exe file, I wrote: "Task.exe <input.txt".
The program ran normally. I mean, it waited for me to input 3 characters.
What have I done wrong in my work?
help me please :)
You are asked to read from an input text file.
Why don't you use fopen to open a file handle, and fgetc to read from it?
You could perhaps use fscanf. Don't forget to use the resulting count.
And of course, you should call fclose. Using perror is useful to handle error cases.
So start your code with something that checks that your program has an argument, then fopen it:
int main(int argc, char**argv) {
if (argc<2) { fprintf(stderr, "missing program argument\n");
exit(EXIT_FAILURE); };
FILE* fil = fopen(argv[1], "r");
if (!fil) { perror(argv[1]); exit(EXIT_FAILURE); };
Then run Task.exe input.txt in your console (no redirection needed!).
You should take the habit of reading the documentation of every function you are using, of testing failure cases, of compiling with all warnings & debug info (gcc -Wall -Wextra -std=c99 -g), and of using the debugger (gdb).

Why am I getting an implicit declaration error for a predefined gtk function?

I am trying to read text in from a file and insert that text into a text box.
This is the code I am using.
FILE *infile;
GdkFont *fixed_font;
infile = fopen("text.txt", "r");
fixed_font = gdk_font_load ("-misc-fixed-medium-r-*-*-*-140-*-*-*-*-*-*");
if (infile) {
char buffer[1024];
int nchars;
while (1)
{
nchars = fread(buffer, 1, 1024, infile);
gtk_text_insert(view, fixed_font, NULL, NULL, buffer, nchars);
if (nchars < 1024)
break;
}
fclose (infile);
These are my includes
#include <gtk/gtk.h>
#include <gtk/gtktext.h>
When I compile I get this warning:
warning: implicit declaration of function ‘gtk_text_insert’
I have read on this forum and others that implicit declaration errors come from using functions before they are declared. However, gtk_text_insert() is included in the header file so how can this be implicit?
I am using the following software:
gtk version 2.20.1
Red Hat Enterprise Linux Server release 6.5
GtkText is deprecated and unsupported. It is known to be buggy. To use it, you must define the symbol GTK_ENABLE_BROKEN prior to including the GTK+ header files. Use GtkTextView instead.
From https://developer.gnome.org/gtk2/stable/GtkText.html

ioctl and hdreg to get information on harddrives

I want to get basic information from a hard-drive and print it out. The most important is that the physical sector size is correct.
For the past few hours I have been fighting with ioctl to get what I want but I can't figure it out.
I have never used ioctl before and I can't seem to find an easy explanation on what exactly you have to do.
Anyway my code looks something like this
int main () {
FILE *driveptr;
int sectorsize;
struct hd_driveid hd;
driveptr=fopen("/dev/sda","r");
if (ioctl(driveptr,HDIO_GET_IDENTITY, &hd)!=0) {
printf("Hard disk model: %s\n",hd.model);
printf("Serial number: %s\n",hd.serial_no);
printf("Sector size: %i\n",hd.sector_bytes);
sectorsize=hd.sector_bytes;
} else {
printf("Error fetching device data.\n");
}
}
In the compiler it throws these warnings, it compiles but the strings are empty when printed.
gcc -o test source.c
source.c: In function ‘main’:
source.c:67:9: warning: passing argument 1 of ‘ioctl’ makes integer from pointer without a cast [enabled by default]
/usr/include/x86_64-linux-gnu/sys/ioctl.h:42:12: note: expected ‘int’ but argument is of type ‘struct FILE *’
I hope somebody can explain to me what goes wrong!
Instead of
if (ioctl(driveptr,HDIO_GET_IDENTITY, &hd)!=0) {
you probably want
if (ioctl(fileno(driveptr),HDIO_GET_IDENTITY, &hd)!= -1) {
^^^^^^^ ^ ^^
Because ioctl's first argument need to be an integer file descriptor not a FILE *
fileno() will give you an integer fd from a FILE *.
Note also that ioctl returns -1 on an error and sets errno.
Reading the man pages of the functions you are using is probably quicker than posting to StackOverflow.
See man pages of ioctl, fileno.

Why is my file pointer causing an undefined symbol error?

This is my code so far:
#include <stdio.h>
int main(void)
{
char filename[50]; /* for holding file's name */
FILE *fp; /* fp is the "file pointer" */
printf("Please enter the name of an input file: ");
scanf("%s", filename);
if (!(fp = fopen(filename, "w"))) /*w=write*/
fprintf(stderr, "unable to open file\a\n");
else {/* process file */
fprintf(fp, "Testing...\n");
}
return 0;
}
The line
FILE *fp;
//is giving me an error Undefined Symbol "FILE"
The line
fprintf(stderr, "unable to open file\a\n");
//is giving me an error Undefined Symbol "stderr"
I thought these keywords were standard C/C++? Why are they giving me errors?
Did you #include <stdio.h>? Also your declaration of main() is incorrect. It should return int, not void.
And no, FILE is not a keyword in either C or C++. Its declaration is in <stdio.h>.
Please add the following line as your 1st statement in your file
#include <stdio.h>
The datatype FILE and functions such as fprint() are defined in this header file and hence you would need that to run your program (tell the compiler the definition of FILE, fprintf() etc)
I had this problem in Visual Studio Code (version 1.67.1) because my c_cpp_properties.json had the "compilerPath" set to "cl.exe", but my tasks.json had "command" set to "clang.exe".
I resolved my issue by copying the path to clang.exe from "command" in tasks.json, and using that for the "compilerPath" value in c_cpp_properties.json.

Resources