The Hive
GitHubLinkedInEmail
  • 🏠Home
  • 🌐RECON
    • 📡Passive (OSINT)
      • ⏩Metadata
      • ⏩Social Platforms
        • Email
        • Tumbler
        • Redit
        • Github
        • Tinder
        • TikTok
        • Snapchat
        • Instagram
        • Facebook
        • Twitter
        • Google
        • LinkedIn
    • 📡Active
      • ⏩Host Discovery / Network Mapping
      • ⏩nmap cheat sheet
      • ⏩masscan cheat sheet
    • 📡Web Recon
      • ⏩Web Server Discovery
      • ⏩Hidden Hosts
      • ⏩Directories & Subdomains
      • ⏩SSL Certs
      • ⏩CMS
      • ⏩WAF Detection
    • 📡Firewall Evasion
  • 📗Web Attacks
    • 🟢Server Side
      • 🟩Authentication Mechanisms
      • 🟩Access Control (Authorization)
      • 🟩Directory Traversal
      • 🟩OS Command Injection
      • 🟩Server-Side Request Forgery (SSRF)
      • 🟩XML External Entity (XXE) Injection
      • 🟩File Upload
      • 🔧SQL Injection
      • 🟩Information Disclosure
      • 🟩Business Logic
    • 🟢Client Side
      • 🟩Cross-site request forgery (CSRF)
      • 🔧Cross-site scripting (XSS)
  • 📒Network attacks
    • 🟡Network Services
      • 🟨Brute Force
      • 🟨DNS
      • 🟨IPv6
      • 🟨FTP
      • 🟨SSH
      • 🟨SMB
      • 🟨SNMP
      • 🟨SMTP
      • 🟨POP3
      • 🟨IMAP
      • 🟨MSSQL
      • 🟨MySQL
      • 🟨MSRPC / RPCbind
      • 🟨LDAP
      • 🟨NTP
      • 🟨NFS
      • 🟨Telnet
      • 🟨WebDAV
      • 🟨RDP
      • 🟨RSIP
      • 🟨Rlogin
      • 🟨VPNs
      • 🟨Echo
      • 🔧RTP
      • 🔧VOIP
        • SIP
    • 🟡Network Devices
      • 🟨IPv6 Attacks
        • Neighbor Impersonation
        • Router Advertisement Flooding
      • 🟨Switch Attacks
        • Cisco Exploitation
        • STP Spoofing
        • VLAN Hopping
        • MAC Flood
      • 🟨Router Attacks
        • Router Exploitation
        • HSRP Hijacking
        • 🔧RIP Spoofing
        • 🔧OSPF Attacks
        • 🔧VRRP MitM
      • 🟨NAC Bypass
        • Captive Portal
        • 802.1X / EAP Bypass
      • 🟨Printer Exploitation
    • 🟡MITM & Poisoning
      • 🟨Bettercap
      • 🟨HTTPS Downgrade / HSTS Bypass
      • 🟨Session Hijackings
      • 🟨Malicious Update
      • 🟨RDP Downgrade
      • 🟨DNS Spoofing
      • 🟨NTP Spoofing
      • 🟨ARP Spoofing
      • 🟨DHCP Poisoning
      • 🟨DHCPv6 Spoofing
      • 🟨SSDP Spoofing
      • 🟨WSUS Spoofing
      • 🟨ADIDNS Poisoning
      • 🟨WPAD Abuse
    • 🟡Wireless Attacks
      • 🟨Protocol Concepts
      • 🟨Basics
      • 🟨Attacks
    • 🟡Sniffing
      • 🟨Wireshark
      • 🟨tcpdump
    • 🟡Denial of Service
  • 📕Red Team
    • 🔴Windows
      • ⭕Security Concepts
        • Windows Security Components
        • Active Directory Components
        • Kerberos
        • Loggon Sessions and Access Tokens
        • Permissions and Access Control
        • Windows Registry
        • Object Management
      • ⭕Physical Attack
      • ⭕Enumeration
      • ⭕Privilege Escalation
        • DLL Hijacking
          • Phantom DLL Hijacking / Replacement
          • Search Order Hijacking ( Preloading )
          • DLL Side-Loading
        • Service Misconfigurations
          • Weak Registry Permissions
          • Insecure Service Executables
          • Insecure Permission
          • Unquoted Service Path
        • Creating a New Service (admin to system)
        • Registry
          • AlwaysInstallElevated
          • AutoRuns
        • Scheduled Tasks
        • Mass Roll-outs
        • Startup Apps
        • Installed Applications
        • Loopback Services
        • Insecure GUI APPs
        • Potatos
        • Printspoofer / SEImpersonate
        • PSEXEC (admin to system)
      • ⭕Credential Dumping
      • ⭕Persistence
        • Invisible Account Forger
        • Add User
        • Scheduled Tasks
        • Run Registry Keys
        • Logon Scripts
        • Screensavers Hijack
        • Powershell Profiles & Modules
        • Service Creation/Modification
        • Shortcut Modification
        • Startup Folder
        • RDP backdoors
        • COM Hijacking
    • 🔴Active Directory
      • ⭕Domain Enumeration
      • ⭕Tools & Frameworks
        • Evil-WinRM
        • CME cheat sheet
        • SharpSploit
        • impacket cheat sheet
        • DeathStar
      • ⭕Exploitation
        • LLMNR Poisoning
        • SMB/NTLM Relay
        • DNS Takeover + LDAP Relay
        • Cracking Hashes
        • Password spraying
        • ADCS + PetitPotam NTLM Relay
        • EternalBlue
        • ZeroLogon
        • MS Exchange ProxyShell
        • MS Exchange ProxyLogon
        • Java JBOSS
      • ⭕Privilege Escalation
        • Token Impersonation
        • DNS Admins
        • AD CS Abuse
        • ACL Abuse
          • GenericAll
          • Write Property
          • Self-membership
          • ForceChangePassword
          • Managed Security Groups
          • Exchange Windows Permissions
        • Group Policy Objects (GPOs)
        • Custom SSPs
        • PrintNightmare
      • ⭕Lateral Movement
        • RDP Password Decryption
        • RDP Session Hijacking
        • headless RDP with SharpRDP
        • Domain Shares
        • SCF File Attacks
        • Pass the Hash / Password
        • Overpass the Hash / Pass the Key
        • Pass The Ticket
        • Kerberosting / AS-REP Rosting
        • Kerberos Delegation
      • ⭕Credential Dumping
        • CredSSP / TSPKG
        • Wdigest Clear Text
        • DPAPI secrets
        • SAM & Registry
        • NTDS.dit & vshadow
        • comsvcs.dll
        • Meterpreter
        • Procdump & LSASS
        • AD User Comments
        • SYSVOL & Group Policy Preferences
        • LAPS Passwords
        • GSMA Passwords
        • HiveNightmare
        • Mimikatz Cheat sheet
        • Other Tools / Techniques
      • ⭕Persistence
        • Certificates
        • DCSync
        • DCShadow
        • Silver Ticket
        • Golden Ticket
        • Skeleton Key
        • WMI
        • PowerShell Remoting
        • Remote Registry
        • Rights Abuse
        • AdminSDHolder
        • DSRM
        • Kerberos Checksum Validation ( MS14-068 )
    • 🔴Linux
      • ⭕Physical Attacks
      • ⭕Enumeration
      • ⭕Privilege Escalation
        • SUID / SGID abuse
        • /etc/shadow & /etc/passwd
        • cron/crontab abuse
        • Sudo Abuse
        • Capabilities Abuse
        • Environment Variables
          • LD_LIBRARY_PATH
          • LD_PRELOAD
        • Shared Object Injection
        • NFS
        • man CE Pager Argument
        • MySQL UDF
        • UDEVD
        • STDIN/STDOUT
        • Unix Socket Exploitation
        • Dirty Pipe
        • Docker
          • SUID Docker
      • ⭕Lateral Movement
        • Infecting Running Processes
        • VIM Config File Keylogger
        • SSH Hijacking
        • Samba Secrets to Domain Admin
        • Hiding Processes
        • Simple User-mode Rootkits
        • Vino VNC Server
      • ⭕Credential Dumping
        • Swap Dump
        • mimipinguin
        • unshadow
        • 3snake
      • ⭕Persistence
        • Startup User File Backdoor
        • PHP Backdoor
        • Apache mod_rootme
        • Startup Service Backdoor
        • xdg Backdoor
        • rootbash SUID
        • apt Backdoor
        • Driver Backdoor
        • Core Pattern
        • dash Backdoor
        • Creating an SUID Binary
        • Systemd netcat bind shell
        • Xinetd UDP portnock
        • openSSL reverse shell
        • motd Backdoor
        • Auth Log Backdoor
        • RSYSLOG Backdoor
        • sshd Backdoor
        • VIM Config Backdoor
        • .bashrc Backdoor
        • Adding a Root user
        • Crontab Reverse Shell
        • SSH persistence password-less
      • ⭕Covering Tracks
    • 🔴Command & Control (C2)
      • ⭕Cobalt Strike
      • ⭕Metasploit
      • ⭕Empire & Starkiller
      • ⭕Covenant
    • 🔴Shells and Payloads
      • ⭕Shell Escape / Interactive Shell
      • ⭕LOL Binaries
      • ⭕msfvenom
      • ⭕SharpShooter & Ivy
      • ⭕Other Payloads
    • 🔴Payload Delivery
      • ⭕Powershell Reflective DLL Load
      • ⭕HTML Smuggling
      • ⭕Office Macros
      • ⭕DDE Auto - Word/Excel
      • ⭕.SLK Excel
      • ⭕XLM Macro 4.0
      • ⭕LNK
      • ⭕embedded OLE + LNK objects
      • ⭕JScript
      • ⭕HTA
      • ⭕VBS
      • ⭕VBA
      • ⭕RTF
      • ⭕REG
      • ⭕MSI / MSIEXEC
      • ⭕IQY
      • ⭕CHM / HHC
      • ⭕SCR
    • 🔴Pivoting
      • ⭕SSH Forwarding
      • ⭕Socat Stealth Port Forward
      • ⭕Socat Reverse Shell Relay
      • ⭕HTTP Tunneling
      • ⭕ICMP Tunneling
      • ⭕DNS Tunneling
      • ⭕Metasploit Pivoting
      • ⭕Cobalt Strike Pivoteing
      • ⭕VPN Tunneling
      • ⭕Other Tools
    • 🔴Exfiltration / File Transfer
      • ⭕Encode / Decode Files
      • ⭕TCP / UDP
      • ⭕DNS
      • ⭕SSH
      • ⭕ICMP
      • ⭕SMB
      • ⭕FTP
      • ⭕HTTP
      • ⭕Other Methods
    • 🔴Password Attacks
      • ⭕Online Attacks
      • ⭕Offline Attack
      • ⭕Word List
      • ⭕Cheat Sheet
    • 🔴Defense Evasion
      • ⭕Basic Tricks
      • 🔧Powershell Tricks
      • ⭕Disabling Defenses
      • ⭕UAC Bypass
      • ⭕Process Migration
      • ⭕Dechaining Macros
      • ⭕VBA Sandbox Evasion
      • ⭕AMSI Bypass
      • ⭕SRP & AppLocker Bypass
      • ⭕GPO Bypass
  • 📘Blue Team
    • 🔵Threat Modeling / Hunting / Intelligence
    • 🔵Linux Hardening
      • 🔹OS Security
        • Update Strategy
        • Service Management
        • Physical Security
        • Grub Hardening
        • Kernel Parameters
        • Process Isolation
      • 🔹Accounts & Passwords
        • Users & Groups
        • Password Security & Sudoers
      • 🔹Access Control & Ownership
      • 🔹File System Security
      • 🔹Integrity Check
      • 🔹Sandboxing
      • 🔹Network
      • 🔹iptables
        • Rule Sets
      • 🔹Service Hardening
        • BIND9
        • vsftpd
        • Nginx
        • Apache
        • SSH
      • 🔹System Audit
      • 🔹Logging
        • auditd
      • 🔹Encryption
    • 🔵Security Architecture
      • 🔹Layered Security
  • 🟪Purple Teaming
    • 🟣Adversary Emulation
  • 🟧programming
    • 🟠C Programming
      • 🔸Basic Structure
      • 🔸GCC Compiler
      • 🔸Preprocessors
      • 🔸Data Types
      • 🔸Type Qualifiers
      • 🔸Pointers
      • 🔸Dynamic Memory Allocation
      • 🔸Loops
      • 🔸Conditional Statements
      • 🔸Functions
      • 🔸Input / Output
      • 🔸Macros
      • 🔸Files
      • 🔸Strings Manipulation
      • 🔸Bit Manipulation
      • 🔸Data Structures
        • Arrays
        • Structures
        • Unions
      • 🔸Abstract Data Types
        • Stack
        • Queue
        • Linked List
          • Singly Linked List
          • Doubly Linked List
      • 🔸Libraries & Linking
      • 🔸Error Recovery
    • 🔧Assembly ( NASM )
      • Intel IA-32 Environment
      • Basic Structure
      • Variables and Data Types
      • Most-used Instructions
      • input / output
  • 🟫Miscellaneous
    • 🟤GNU Screen / tmux
    • 🟤SSH Tricks
    • 🟤Cats
      • netcat
      • ncat
      • pwncat
      • socat
      • 🔧powercat
    • 🟤Curl
    • 🟤Cross-compiling Binaries
Powered by GitBook
On this page
  • char functions (input)
  • char functions (output)
  • string functions(input)
  • Formatting functions
  • Printing system error messages
  1. programming
  2. C Programming

Input / Output

<stdio.h>

PreviousFunctionsNextMacros

Last updated 2 years ago

char functions (input)

int getc(FILE *stream); → read a single character from a file

example read from a file:

#include <stdio.h>
int main(){
    char ch = '\0';
    FILE *fp;
    if (fp = fopen("test","rw")){
        ch = getc(fp);
        while (ch != EOF)
        {
            printf("%c",ch);
            ch = getc(fp);
        }
        fclose(fp);
    }
    return 0;
}

example read from stdin ( i.e: keyboard):

int main(){
        char ch = '\0';
        ch = getc(stdin);
        printf(">>> %c\n",ch);
    return 0;
}

we can do it this way too:

int main(){
    int ch = 0;
    while ((ch = getchar()) != EOF)
    printf("%c\n",ch);
    return 0;
}

we can do it with catching spaces:

int main(){
    int ch = 0;
    while (isspace(ch = (char)getchar()));
    printf("%c\n",ch);
    return 0;
}

int ungetc(int char, FILE *stream); → pushes the character char (an unsigned char) into the specified stream so that this is available for the next read operation.

#include <stdio.h>

int main () {
    FILE *fp;
    int c;
    char buffer [256];

    fp = fopen("test", "r");
    if( fp == NULL ) {
        perror("Error in opening file");
        return(-1);
    }
    while(!feof(fp)) {7h3w4lk3r/The-Hive
        c = getc (fp);
        /* replace ! with + */
        if( c == '!' ) {
            ungetc ('+', fp);
        } else {
            ungetc(c, fp);
        }
        fgets(buffer, 255, fp);
        fputs(buffer, stdout);
    }
    return(0);
}

char functions (output)

int putc(int char, FILE *fp) → write a single character to a file or stdout

putc('\n',stdout);

takes 2 args:

1.character

2.file pointer

example redirecting the input to a file:

int main(){
int ch = 0;
while ((ch = getchar()) != EOF)
    putchar(ch);
ungetc(ch, stdin); // returns EOF previously read back to stdin
printf("EOF signal detected!\n");
return 0;
}

use the above program like this:

./main < infile

int fputc(int character, FILE *stream); → writes a character (an unsigned char) to the specified stream and advances the position indicator for the stream.

example write characters a-z in a file:

int main(){
FILE *pfile = NULL;
char c = '\0';

pfile = fopen("test","w");
if (pfile != NULL){
    for (c = 'A'; c <= 'Z'; c++)
        fputc(c,pfile);
    fclose(pfile);
}
return 0;
}

example count the number of characters and words in a file or from stdin:

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

int main(int argc, char *argv[]){
    FILE * fp = NULL;
    char ch = '\0';
    int wrd = 1, character = 1;

    if (argc==1)
        fp = stdin;
    else if (argc == 2){
        if ((fp = fopen(argv[1], "r")) == NULL){
            fprintf(stderr, "cant open the file %s\n",argv[1]);
            exit(EXIT_FAILURE);
        }
    }
    else {
        fprintf(stderr, "usage: %s [filenme]\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    ch = getc(fp);
    while (ch != EOF){
        if (ch ==' ' || ch=='\n'){
            wrd++;
        }
        else {
            character++;
        }

        ch = getc(fp);
    }
printf("\n the number of words : %d\n",wrd-1);
printf("the number of characters: %d\n",character-1);

return 0;
}

to enter EOF press Ctrl+D keys

example convert uppercase to lowercase and vice versa in a file and stdin:

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

void convertCase(FILE * fptr, const char *path);


int main(){
    FILE * fptr = NULL;
    char path[100];
    printf("enter the full path to the file: ");
    scanf("%s",path);
    fptr = fopen(path, "r");
    if (fptr == NULL){
        fprintf(stderr,"unable to open file. \n");
        exit(EXIT_FAILURE);
    }
    convertCase(fptr,path);
    return 0;
}

void convertCase(FILE * fptr, const char *path){
    FILE *dest = NULL;
    char ch = '\0';
    dest = fopen("output","w");
        if (dest == NULL){
        fprintf(stderr,"unable to open file. \n");
        exit(EXIT_FAILURE);
    }
        while ((ch = fgetc(fptr)) != EOF){
            if (isupper(ch))
                ch = tolower(ch);
            else if (islower(ch))
                ch = toupper(ch);
            fputc(ch, dest);
        }
fclose(fptr);
fclose(dest);
remove(path);
rename("output",path);

string functions(input)

ssize_t getline(char *buffer,size_t size, FILE *stream);

buffer → a pointer to a block allocated with malloc or calloc (type char **)

there is never a shortage of space cause it automatically enlarge the block of memory using realloc as needed ( getline is safe) returns the line read by getline

example:

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

int main(){
    char *buffer = NULL;
    size_t bufsize = 32;
    size_t characters;
    buffer = (char *)malloc(bufsize * sizeof(char));
    if (buffer == NULL){
        exit(1);
    }
    printf("type something: ");
    characters = getline(&buffer, &bufsize,stdin);
    printf("%zu characters were read\n",characters);
    printf(" you typed: %s\n",buffer);
    return 0;
}

int fscanf(FILE _fp, const char_** format [,argument,...]);** → same as printf but on a file. returns the number of arguments that are successfully read and assigned (on success), returns EOF if the end of the file is reached before any of the conversion specifications have been processed

fscanf(myFile, "%i", &i); → reads the next integer value from the file "myFile" and stores it in the variable i

example:

#include <stdio.h>
int main() {
    FILE *fp;
    char buff[255];
    fp = fopen("test","r");
    while (fscanf(fp,"%s",buff)!=EOF){
        printf("%s ", buff);
    }
    fclose(fp);
  return 0;
}

Formatting functions

int sprintf(char _string, const char_** format,...)** → used to write formatted output to a string. we can combine several data variables into a character array, instead of printing on the console we store the output to a char buffer

sprintf(string, "%d %c %f", value, c, fit);

first parameter is a char pointer for output(buffer) the function returns the number of characters stored in the string

this function is unsafe and vulnerable to buffer overflow

#include <stdio.h>

int main() {
    char string[100];
    int a = 10, b=20, c= 0;
    c = a + b;
    sprintf(string, "sum of %d and %d is %d",a,b,c);
    puts(string);
  return 0;
}

sscanf(const char _str, const char_** control_string [arg1,arg2,...]);** → allows to read formatted data from a string rather than stdin or keyboard

sscanf(buffer,"%s %d", name,&age);

first arg is a pointer to string from where to read the data returns the number of items read from the string and -1 if an error is encountered

example:

#include <stdio.h>

int main() {
    char *str = "jason fedin 43";
    char name[10], title[10];
    int age, ret;

    ret = sscanf(str, "%s %s %d", name ,title, &age);

    printf("name: %s\n",name);
    printf("title: %s\n",title);
    printf("age: %d\n",age);

  return ret;
}

fflush() → used to flush/clean a file or buffer

int fflush(FILE *fp);
fflush(buffer);

for float and double values we can print a specific width of the value like this:

float floatValue = 432.476868734;
printf("float with width of 3 : %.3f",floatValue); → %.3f only print the first 3 sections

output: 432.476

for integer input always use '&' before variable name

#include <stdio.h>
int main() {
    char str[100];
    int i;
    printf("Enter a value:");
    scanf("%d", &i);
    printf("\nYou entered: %d\n", i);   
    return 0;}

Printing system error messages

perror("error text"); → used for printing error messages followed by system stderr

returns the number of items that it successfully reads . while using scanf() to read a value for one of the basic variable types, prepend the variable name with an & sign . while using scanf() to read a string into a character array, don't use an & sign.example:

🟧
🟠
🔸