开发者

How can I return a string to the operating system in my C code?

开发者 https://www.devze.com 2023-02-09 07:57 出处:网络
I am a C beginner and this is my C code: #include <stdio.h> #include <stdlib.h> main() { printf(\"Hello, World!\\n\");

I am a C beginner and this is my C code:

#include <stdio.h>
#include <stdlib.h>

main()
{
    printf("Hello, World!\n");
    return 'sss';
}

That will show an e开发者_开发问答rror. So how can I return a string in C code?


If you are looking to return a string from a function (other than main), you should do something like this.

#include <stdio.h>

const char * getString();

int main()
{
    printf("Hello, World!\n");
    printf("%s\n", getString());
    return 0;
}

const char * getString()
{
    const char *x = "abcstring";
    return x;
}


The magic is in the key word static which preserves the memory content of the string even after the function ends. (You can consider it like extending the scope of the variable.)

This code takes one character each time, then concatenates them in a string and saves it into a file:

#include <stdio.h>
#include <conio.h>

char* strbsmallah ()
{
  static char input[50];
  char position = 0, letter;
  scanf("%c", &letter);
  while (letter != '~') { // Press '~' to end your text
    input[position] = letter;
    ++position;
    scanf("%c", &letter);
  }
  input[position] = '\0';
  char *y;
  y = (char*) &input;
  //printf("%s\n ", y);
  return y;
}

int main() {
  printf("\n");
  FILE *fp;
  fp = fopen("bsmallah.txt", "w+");
  fprintf(fp, strbsmallah());

  while (!_kbhit())
    ;

  return 0;
}


You could do this in a way similar to scanf. In other words:

void foo(char **value_to_return) {
    *value_to_return = malloc(256); // Store 256 characters
    strcpy(*value_to_return, "deposited string");
}

int main() {
    char *deposit;
    foo(&deposit);
    printf("%s", deposit);
    return 0;
}


You don't return a string. Applications exit with an integer exit code.

Conventionally, exiting with a return of 0 will always show that your application exited without error / completed. You return an integer other than 0 to show that your application exited abnormally.

You could throw an exception and handle it with a logging method higher in the call stack, or you could just return something other than 0 and make sure you had it documented in your release notes as to what each error integer means.


Sadly there is no way to do that.

You could add something to the end of your C program like:

int main()
{
    int err = 0; // 0 is "success" is most C programs
    printf("Hello, World!!\n");

    switch( err )
    {
      case 0:
        printf("Program shutdown successfully!\n");
        break;
      case 1:
        printf("We had an issue somewhere. Please fix your input data\n");
        break;
      //case 2, 3, etc...
    };

   return err;
}


You might be able to use environment variables for that. Not sure though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号