Scanning input into a malloc pointer not working - c

I have this code but it's not working. No matter what I type it prints nothing.
#include <stdio.h>
#include <stdlib.h>
char *askFile()
{
printf("Enter a file: ");
char *file = malloc(512 * sizeof(char));
scanf("%s", file);
return file;
}
int main()
{
char *file = askFile();
printf("%s", *file);
return 0;
}
Why doesn't it work?

As #Someprogrammerdude said in the comments the mistake was:
printf("%s", *file);
It was supposed to be:
printf("%s", file);
Since *file points to the first element.

The key mistake is not using a good compiler with all warnings enabled. A good well-enabled compiler would have warned about the specifier-type mismatch.
char *file =...;
printf("%s", *file); // Warning expected.
Save time. Enable all compiler warnings.

Related

Copy lines from file to char *array[]?

Hi need a little bit of help here. I have a file with 5 lines and I want to put this lines into an array of type char *lines[5]; but I can't figure it out why the following isn't working.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("name.txt", "r");
char *str;
char *list[5];
int i = 0;
while (fgets(str, 100, fp) != NULL) // read line of text
{
printf("%s", str);
strcpy(list[i], str);
i++;
}
}
As the commenters stated, you need to create an array (which is nothing more than a space in the memory) of a sufficient size to store your string. One approach to solve your problems is the following, note the comments:
#include <stdio.h>
#include <string.h>
int lines(FILE *file); //try to format the code according to some standard
int main(void) {
FILE *fp = fopen("name.txt", "r");
char list[5][100]; //make sure you allocate enough space for your message
// for loop is more elegant than while loop in this case,
// as you have an index which increases anyway.
// also, you can make sure that files with more than 5 lines
// do not break your program.
for(int i = 0; i<5 ;++i )
{
if(fgets(list[i], 100, fp) == NULL){
break;
}
//list[i] is already a string, you don't need an extra copy
printf("%s", list[i]);
}
}

Char Array Declaration Crashes Program

So, I'm getting a really weird error in my program, and I've narrowed it down to something to do with getline() and declaring an array of size greater than 8. However, I'm super confused as to why it's doing that, so any help or explanation is greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
void populateConfig();
int main(int arc, char *argv[])
{
// when thing is size 8 it works fine
char thing[9];
populateConfig();
return 0;
}
void populateConfig(){
FILE *fp;
char string1[1000], string2[1000];
char *line;
int len = 0;
fp = fopen("ws.conf", "r");
while(fscanf(fp, "%s", string1) != -1){
// Commenting out if statement prevents crash
if(string1[0] == '#'){
getline(&line, &len, fp);
continue;
}
}
fclose(fp);
}
So I'm just reading in a config file, and as shown, when I change the size of thing to 8 or less, it works, and when I comment out the if statement in populateConfig() it also works. Is this something to do with the stack or memory? Should I do something differently?
You need to initialize char *line to NULL first. Then before returning, free it.
https://linux.die.net/man/3/getline

Why am I getting a hyphen at start of file?

I am learning C and I have tried to build a program that outputs its own source. This is my source:
#include <stdio.h>
int S = 512;
int main(){
FILE * fp;
fp = fopen("hello.c","r");
char * line = (char *) malloc(S);
int i = 0;
while (i == 0)
{
i = feof(fp);
printf("%s",line);
fgets(line,S,fp);
}
fclose(fp);
}
I have used the tcc compiler and I got this output:
But notice, I got a hyphen before #include. The rest of the output is correct.
So please can someone explain why I got this hyphen??
You're printing the first line before you've read anything.
#include <stdio.h>
int main(){
FILE *fp = fopen("hello.c", "r");
char line[256];
while (fgets(line, sizeof line, fp) != NULL)
printf("%s",line);
fclose(fp);
return 0;
}
#ooga gave you the correct answer.
The why is that malloc doesn't initialize the memory before it returns it to you, unlike its sister calloc.
Most likely, on another platform / compiler, you'd get something different.
Some compilers use a debug heap that initializes "unitialized" memory to a specific value. The release mode will probably result in random garbage instead of a '-' everytime.

Write an output file with a user defined name in C

I am new to C and am trying to define an output filename before the program runs. I am getting a Bus error
Here is my code:
#include <stdio.h>
int main (int argc, const char * argv[]) {
char fname[128];
printf("Enter the file name\n");
scanf("%123s",fname);
strcat("/Users/user/Desktop/learn/", fname);
strcat(fname, ".txt");
FILE *fp;
fp=fopen(fname,"a");
fprintf(fp, "Testing... OK I think it worked\n");
return 0;
}
You didn't #include <string.h> for strcat.
The first argument to strcat must be a pointer, not a string literal.
strcat itself isn't safe, use strncat instead.
Don't forget to check the result of scanf and fopen.
And close fp when you're done with it.
The signature of main should be int main(int argc, char * argv[]).
The use of scanf is also generally discouraged, use fscanf & sscanf instead.
You are using a string literal as the destination pointer in the first call to strcat. so you are concatonating "/Users/user/Desktop/learn/" with fname and storing the result where ever "/Users/user/Desktop/learn/" was stored, which might not even be writable.
That's not how strcat() works.
I see two approaches:
Use fname correctly, together with the file name inputting:
char fname[128];
strcpy(fname, "/Users/user/Desktop/learn/"); // ok as long as you don't make the 128 too small
char * input = fname + strlen(fname); // now points after the final /
printf("Enter the file name\n");
scanf("%123s", input); // the 123 is probably not correct
strncat(fname, ".txt", sizeof fname);
and use it.
Currently, this approach is still suffering from the fact that input is limited to 123 bytes, which might be too large, so better forget it for now. It is just for getting the idea.
Maybe fgets() might be better:
fgets(input, sizeof(fname)-strlen(fname), stdin);
Use command line parameters, which would be my favourite approach:
// first check if argc is >= 2, i. e. if the caller has supplied an argument
char fname[128];
strcpy(fname, "/Users/user/Desktop/learn/");
strncat(fname, argv[1], sizeof fname);
strncat(fname, ".txt", sizeof fname);
Try this, this is worked for me..
http://cboard.cprogramming.com/c-programming/124576-whats-mean-char*-const*-argv.html
#include <stdio.h>
#include <string.h>
int main (int argc, const char*const* argv[])
{
char fname[128];
char path[] = "/home/abc/test/";
printf("Enter the file name\n");
scanf("%123s",fname);
strcat(fname,".txt");
strcat(path,fname);
FILE *fp;
fp=fopen(path,"a");
fprintf(fp, "Testing... OK I think it worked\n");
fclose(fp);
return 0;
}
Thanks for everyone's comments. This was working code:
#include <stdio.h>
#include <string.h>
int main (int argc, const char*const* argv[])
{
char fname[128];
strcpy(fname, "/Users/user/Desktop/learn/");
char * input = fname + strlen(fname);
printf("Enter the file name\n");
scanf("%s", input);
strncat(fname, ".txt", sizeof fname);
printf("The output pathway and file will be called %s\n", fname);
FILE *fp;
fp=fopen(fname,"a");
fprintf(fp, "Testing... OK I think it worked\n");
fclose(fp);
return 0;
}

Why am I getting this compiler error referencing a line from a different function?

I'm just trying to pass copywords from the function get_string in to fileinput in main.
the compiler says error in function get_string while referencing line 5 which is the first line of main.
#include <stdio.h>
#include <stdlib.h>
char get_string (char * copywords[100])
int main (){
char fileinput[100];
get_string(fileinput[100]);
;
char get_string (char * copywords[100]) {
FILE *fp;
int c;
char copywords[100];
fp = fopen("gues20.txt", "r");
if (fp == NULL)
exit(1);
else {
while(fgets(copywords , 100, fp) == EOF){
}
fclose(fp);
}
return (copywords);
}
You're missing a semicolon in the prototype for get_string(), right before main().
char get_string (char * copywords[100]);
^
|
IMPORTANT
This causes the function definitions to nest, which is not allowed.
You don't have a semicolon after the declaration of get_string, so the compiler doesn't know that the declaration is over and when it sees the int from int main, it gets confused because int isn't legal after the parameter list of a function declaration.
PS: Your main function also doesn't have a closing brace, but that's a different issue.
If you use a tool or editor which indent your code for you, you will see at a glance that there something odd. You are missing a ; and that's a reason. Then, you put a ; where likely a } should go, and so there is an unbalanced {. Do not underestimate how useful it could be for you and for any reader a well indented and presented code.
#include <stdio.h>
#include <stdlib.h>
char get_string (char * copywords[100]);
int main (){
char fileinput[100];
get_string(fileinput[100]);
}
char get_string (char * copywords[100]) {
FILE *fp;
int c;
char copywords[100]; // redeclared
fp = fopen("gues20.txt", "r");
if (fp == NULL)
exit(1);
else {
while(fgets(copywords , 100, fp) == EOF) ; // ??
fclose(fp);
}
return copywords; // (*)
}
Your code shows other errors, like redeclaring of copywords, returning a pointers (to a memory area that will be invalid) instead of a char. Briefly, your code won't compile and even if you strive to make it compilable, likely it won't do what you want.

Resources