Skip to content

Instantly share code, notes, and snippets.

@carlfriess
Last active October 11, 2017 12:09
Show Gist options
  • Save carlfriess/388f765557ee8c4bf93ec34fc98b2030 to your computer and use it in GitHub Desktop.
Save carlfriess/388f765557ee8c4bf93ec34fc98b2030 to your computer and use it in GitHub Desktop.
SPCA: Cheatsheet for Assignment 3
/*
* =================================
* SPCA: Cheatsheet for Assignment 3
* Carl Friess
* =================================
*/
// Reading arguments
// Example: $ nano myfile.txt
int main(int argc, char* argv[])
{
// Number of arguments (aka length of the argv array)
int numArguments = argc; // 2
// Program name
char *firstArgument = argv[0]; // "nano"
// First argument passed to the program
char *secondArgument = argv[1]; // "myfile.txt"
}
// Create file pointer
FILE *fp = NULL;
// Use stdin
fp = stdin;
// Open a file for reading
fp = fopen("myfile.txt", "r");
// Read a single char
char c = fgetc(fp);
// Check if a char is white space
if (isspace(c)) {
printf("'%c' is white space!", c);
}
else {
printf("'%c' is not white space!", c);
}
// Read pattern from string
char string[] = "15th May";
int day;
char month[10];
sscanf(string, "%dth %s", &day, month);
// Read line from file
#define MAX_STRING_LENGTH 50
char line[MAX_STRING_LENGTH];
if (fgets(string, MAX_STRING_LENGTH, fp)) {
/* Read successful */
}
// Write to file with format
fprintf(fp, "%dth %s\n", day, month);
// Closing a file when done with it
fclose(fp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment