And Now I'm BACK, From USERSPACE!!..... :3

B

blackneos940

Guest
So anyway, we all know that you can append things to the end of Files in Python, like this little example here from my SA2B_Checklist Program..... :3

Code:
animal_name = input("Type the Animal's name now:\n>>> ").capitalize()

with open(file_name + ".txt", "wb") as le_output:

  #Following Code goes HERE.   :3

But how do we do it in C.....? :< I do

Code:
#include <stdio.h>

#include <stdlib.h>

#define PI 3.14

int main(void)

{
  int file_name;

  printf ("Want to make a File?\nType a File Name now. :)\n");

  scanf ("%d", &file_name);

  FILE *f_ptr = fopen (file_name + ".txt", "w");

  if (f_ptr == NULL)

  {
  printf ("Could not write to file.\n");

  }

  fprintf (f_ptr, "Hello World!!\n");

  fflush (f_ptr);

  fclose (f_ptr);

/*Rest of Program goes here*/

it throws me a "Segmentation Fault" error when I try and run it..... :< What's up with that....? :( Thanks for any help, guys....... :3
 


Hey, long time no see!
Been a bit busy recently, so haven't had much time to get online.
It's been a while since I did any low level C programming too. But there are a number of things that are wrong with your code.

Firstly, the file name will not be an integer, it will be a c-style string - an array of characters.
Secondly, you need to get the file name as a c-style string (%s), not as int (%d).
Thirdly, you can't use the + operator to append text to a string in C. In C you need to use strncat.
Finally: If the file fails to open, you have the program outputting an error message via printf, but immediately afterwards, you attempt to write to the file anyway. This is the cause of the seg-fault/crash you are seeing.
What is happening is the call to fopen is failing (because of a combination of the problems above), you output an error message and then immediately attempt to write to an invalid file handle... Then Boom! :)
At the point of failure, it might be wiser to exit the program. Or separate the code for the two states with an if..else...

Here's a heavily commented and updated version of your code for your consideration:
(The comments should hopefully explain everything I've done)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* for strncat */
#include <linux/limits.h> /* for PATH_MAX */

#define PI 3.14

int main(void)
{
  /* Get the user to enter the file name as a string */
  char raw_name[PATH_MAX];
  printf ("Want to make a File?\nType a File Name now. :)\n");
  scanf ("%s", raw_name);

  /* Concatenate .txt onto the end of the file name
  But what if the user already specified .txt? This would append .txt again!
  Just something for you to consider! Maybe add a function to check the filename and see if we need to append an extension?!

  Anyway, strncat returns a char * which we assign to the variable file_name.
  The first parameter (raw_name) is the destination string we want to append additional characters to
  The second param (".txt") is the source string we want to append to the destination string
  The third parameter is the number of bytes to copy from the source string (2nd parameter). ".txt" is 4 characters, so we require 4*sizeof(char) bytes
  */
  char *file_name = strncat(raw_name, ".txt", 4*sizeof(char));

  /* Open the file */
  FILE *f_ptr = fopen (file_name, "w");

  /* If the file opened successfully, write to the file and close it again */
  if(f_ptr)
{
    fprintf (f_ptr, "Hello World!!\n");
    fflush (f_ptr);
    fclose (f_ptr);
}
else
{
    printf ("Could not write to file.\n");
    /* return EXIT_FAILURE; /* Optionally, you might want to exit with an error status */
}

  /*Rest of Program goes here*/
  return EXIT_SUCCESS; /* EXIT_SUCCESS and EXIT_FAILURE are defined in stdlib.h */
}

BTW: If you actually want to append text to the end of the file, you might also want to consider opening the file using the a or a+ flag. The w flag opens the file for writing, but will always overwrite the file from the beginning. Whereas a will append to the end of the file (or create a new file - if a file with the specified name does not exist) and a+ will append to the end of the file, but ONLY if the file already exists - If my memory serves me correctly!

Hope this has helped. Any further questions, fire away! :)
 
Last edited:
Hey, long time no see!
Been a bit busy recently, so haven't had much time to get online.
It's been a while since I did any low level C programming too. But there are a number of things that are wrong with your code.

Firstly, the file name will not be an integer, it will be a c-style string - an array of characters.
Secondly, you need to get the file name as a c-style string (%s), not as int (%d).
Thirdly, you can't use the + operator to append text to a string in C. In C you need to use strncat.
Finally: If the file fails to open, you have the program outputting an error message via printf, but immediately afterwards, you attempt to write to the file anyway. This is the cause of the seg-fault/crash you are seeing.
What is happening is the call to fopen is failing (because of a combination of the problems above), you output an error message and then immediately attempt to write to an invalid file handle... Then Boom! :)
At the point of failure, it might be wiser to exit the program. Or separate the code for the two states with an if..else...

Here's a heavily commented and updated version of your code for your consideration:
(The comments should hopefully explain everything I've done)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* for strncat */
#include <linux/limits.h> /* for PATH_MAX */

#define PI 3.14

int main(void)
{
  /* Get the user to enter the file name as a string */
  char raw_name[PATH_MAX];
  printf ("Want to make a File?\nType a File Name now. :)\n");
  scanf ("%s", raw_name);

  /* Concatenate .txt onto the end of the file name
  But what if the user already specified .txt? This would append .txt again!
  Just something for you to consider! Maybe add a function to check the filename and see if we need to append an extension?!

  Anyway, strncat returns a char * which we assign to the variable file_name.
  The first parameter (raw_name) is the destination string we want to append additional characters to
  The second param (".txt") is the source string we want to append to the destination string
  The third parameter is the number of bytes to copy from the source string (2nd parameter). ".txt" is 4 characters, so we require 4*sizeof(char) bytes
  */
  char *file_name = strncat(raw_name, ".txt", 4*sizeof(char));

  /* Open the file */
  FILE *f_ptr = fopen (file_name, "w");

  /* If the file opened successfully, write to the file and close it again */
  if(f_ptr)
{
    fprintf (f_ptr, "Hello World!!\n");
    fflush (f_ptr);
    fclose (f_ptr);
}
else
{
    printf ("Could not write to file.\n");
    /* return EXIT_FAILURE; /* Optionally, you might want to exit with an error status */
}

  /*Rest of Program goes here*/
  return EXIT_SUCCESS; /* EXIT_SUCCESS and EXIT_FAILURE are defined in stdlib.h */
}

BTW: If you actually want to append text to the end of the file, you might also want to consider opening the file using the a or a+ flag. The w flag opens the file for writing, but will always overwrite the file from the beginning. Whereas a will append to the end of the file (or create a new file - if a file with the specified name does not exist) and a+ will append to the end of the file, but ONLY if the file already exists - If my memory serves me correctly!

Hope this has helped. Any further questions, fire away! :)
Man..... That many Errors.....? *Sigh*..... :( I... I won't give up, but you know what.....? It sucks trying to learn how to Code all by yourself..... And now, I've got an Error with ANOTHER Practice File I made, that speaks of "warning: assignment makes integer from pointer from integer without a cast." :( Look at this Code: do you see ANYthing to do with "*char" in the first part.....? :(
Code:
/*The goal of this program is to test my skills in utilizing Switch Statements, coupled with initiating 2 Switch Statements*/

#include <stdio.h>

int main(void)

{
  int test;

  test = 1; /*Here is the FIRST Integer, being given a Value of "1"*/

  int test_two;

  test_two = "Fuzzy Mittens."; /*And the SECOND Integer, being given a String Value of "Fuzzy Mittens."*/

/*Rest of Program*/...

}

My God...... Right now, I wanna cry..... What I would only GIVE to be able to Program in my sleep, like some of you on here..... I keep trying, but always come up short....... Plus, things aren't going so well in my Life right now..... Someone else is sick, and I just dealt with my Father's death..... I don't care if those clowns from that Website who DOX'ed me see this....... Sorry guys..... I really need to learn how to use the IRC.... This isn't the place for this sort of thing..... But if any of you need an ear--- er, a localhost--- to listen in on your troubled past, then I'll be here..... Ok....? :') Thanks for the help guys..... And I'll study your revision of that Code, ok Jas.....? :') Take care......
 
Last edited:
An int isn't a generic variable declaration. It is a specific datatype. An integer variable cannot and will not store a string value. Try to use c-strings. Since there is no string datatype in C, you could use something like this:
Code:
char test_two[someLengthGreaterThanTheStringLengthPlusOne];
(with an integer value instead of 'someLengthGreaterThanTheStringLengthPlusOne').
You then could assign a value to test_two:
Code:
test_two = "Fuzzy Mittens.";

The reason it talks about type casting is because it doesn't want you to attempt to assign a string literal to an integer variable. Type casting, if you're interested, is a way of explicitly converting between data types, which for example, can be used to convert a floating-point (called a float) variable to an integer.
 
An int isn't a generic variable declaration. It is a specific datatype. An integer variable cannot and will not store a string value. Try to use c-strings. Since there is no string datatype in C, you could use something like this:
Code:
char test_two[someLengthGreaterThanTheStringLengthPlusOne];
(with an integer value instead of 'someLengthGreaterThanTheStringLengthPlusOne').
You then could assign a value to test_two:
Code:
test_two = "Fuzzy Mittens.";

The reason it talks about type casting is because it doesn't want you to attempt to assign a string literal to an integer variable. Type casting, if you're interested, is a way of explicitly converting between data types, which for example, can be used to convert a floating-point (called a float) variable to an integer.
Hello, good sir..... :) Happy New Year!!....... ^^ Anywho, thanks for the help!..... :3 So, I did what you said, and it came up with this....

Switch_Palace.c: In function ‘main’:
Switch_Palace.c:14:12: error: incompatible types when assigning to type ‘char[15]’ from type ‘char *’
test_two = "Fuzzy Mittens."; /*And the SECOND Integer, being given a String Value of "Fuzzy Mittens."*/

I even put one more space for the "\O" Character that the Compiler, GCC, assigns.... :\ What could have gone wrong, I wonder.....? :(
 
Hello, good sir..... :) Happy New Year!!....... ^^ Anywho, thanks for the help!..... :3 So, I did what you said, and it came up with this....

Switch_Palace.c: In function ‘main’:
Switch_Palace.c:14:12: error: incompatible types when assigning to type ‘char[15]’ from type ‘char *’
test_two = "Fuzzy Mittens."; /*And the SECOND Integer, being given a String Value of "Fuzzy Mittens."*/

I even put one more space for the "\O" Character that the Compiler, GCC, assigns.... :\ What could have gone wrong, I wonder.....? :(
Happy new year to you too bud! Try assigning it in the same statement. (I was thinking of C++ previously :oops:)
Code:
char test_two[someLengthGreaterThanTheStringLengthPlusOne] = "Fuzzy Mittens.";
OR
Code:
#include <string.h> // for strncpy function
/* CUT HERE */
int main()
{
/* CUT HERE */
    char test_two[someLengthGreaterThanTheStringLengthPlusOne];
    strncpy(test_two, "Fuzzy Mittens.", someLengthGreaterThanTheStringLengthPlusOne);
Make sure that 'someLengthGreaterThanTheStringLengthPlusOne' is the same value in both places.
By the way it should be 'backslash zero', not 'backslash uppercase letter o'
 
Last edited:
Happy new year to you too bud! Try assigning it in the same statement. (I was thinking of C++ previously :oops:)
Code:
char test_two[someLengthGreaterThanTheStringLengthPlusOne] = "Fuzzy Mittens.";
OR
Code:
#include <string.h> // for strncpy function
/* CUT HERE */
int main()
{
/* CUT HERE */
    char test_two[someLengthGreaterThanTheStringLengthPlusOne];
    strncpy(test_two, "Fuzzy Mittens.", someLengthGreaterThanTheStringLengthPlusOne);
Make sure that 'someLengthGreaterThanTheStringLengthPlusOne' is the same value in both places.
By the way it should be 'backslash zero', not 'backslash uppercase letter o'
Thanks, good sir!..... ^^ I also hope to be able to go to College this year..... :3 Anywho..... :3 Ah, well....... :) To a Novice like me, C and C++ might be hard to differentiate from sometimes....... :) Ok, then..... :3 I'll keep those things in mind!!..... ^^ BTW, I have some Code on GitHub now..... :3 I figure it would be easier to help me out in situations like this if my Code is readily available..... :3 Also, really.....? o_O Man, Lowercase "O" and 0 REALLY confuse me..... :(
 

Members online


Top