clang-format with only minimal specific rules - no defaults - clang-format

I'm using clang-format and I'm trying to only set e.g. 120 column limit but no matter what I try clang applies many rules besides that. If I specify all the rules and set their values then it does what I want but I, e.g., only want to set a line wrap rule. Can clang-format do that?
Thanks
Here's my .clang-format file which is in a parent dir of the source file:
---
Language: Cpp
ColumnLimit: 120
...
Note that I don't have a BasedOnStyle field so I'd expect clang won't use defaults from style.
Here's how I run:
clang-format -style=file -i src/foo.cpp
Here's foo.cpp
int main(int argc, char const *argv[]) {
int rc = -1;
// This if clause should be wrapped at 120 by clang which it does
if (argc == 1 && && argc != 2 && argc != 3 && argc != 4 && argc != 5 && argc != 6 && argc != 7 && argc != 8 && argc != 9 && argc != 10) {
rc = 0;
}
// This if clause shouldn't be touched by clang. but it is.
if(args > 1)
{
rc = 1;
}
return rc;
}
Expected result:
Only lines longer than 120 chars are wrapped.
int main(int argc, char const *argv[]) {
int rc = -1;
// This if clause should be wrapped at 120 by clang which it does
if (argc == 1 && && argc != 2 && argc != 3 && argc != 4 && argc != 5 && argc != 6 && argc != 7 && argc != 8 &&
argc != 9 && argc != 10) {
rc = 0;
}
// This if clause shouldn't be touched by clang. but it is.
if(args > 1)
{
rc = 1;
}
return rc;
}
Actual Result:
Many rules are applied and every line is changed. In this case e.g. indentation becomes 2 spaces. I a real world example many rules are applied to files with more code.
int main(int argc, char const *argv[]) {
int rc = -1;
// This if clause should be wrapped at 120 by clang which it does
if (argc == 1 && &&argc != 2 && argc != 3 && argc != 4 && argc != 5 && argc != 6 && argc != 7 && argc != 8 &&
argc != 9 && argc != 10) {
rc = 0;
}
// This if clause shouldn't be touched by clang. but it is.
if (args > 1) {
rc = 1;
}
return rc;
}

This question is a duplicate of How can I apply only one clang-format action?
The accepted answer to that question is still correct/valid, hence what you are asking is not possible with the latest version of clang-format.

Related

Linked list of leaf files and directories in a dir tree using C

I'm using nftw(file tree walk) for traversing a dir(which has sub-directories and files). I've passed a directory using CLI function. Now I need to store the leaf files and dirs(empty dirs) into a linked list and print them out. I've create a function for nftw called as disp & passed it to nftw so that it'll print out some info about the files. The linked list stores the info of file produced by stat & for printing the linked Linked list printll function is used.
For files I can check that typeflag == FTW_F and then enter the following but how do I check empty directories in nftw and add them to the linked list?
I've tried the following
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <ftw.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
typedef struct node{
long ino; //Inode number
long f_size; //file size
long a_tm; //Access time
long m_tm; //Modify time
long c_tm; //change time
struct node *next;
}node;
node *tmp = NULL;
static node *head = NULL;
void printll(node *head);
//display function
static int disp(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw);
//Function to create linked list
static int linked(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw);
/* ------------------Main---------------------*/
int main(int argc, char *argv[]){
int flags = 0;
if(argc > 2 && strchr(argv[2], 'd') != NULL)
flags |= FTW_DEPTH;
printf("File_type\tF_size\t\tPath\t\t\t\t\t\t\tInode\n");
if(nftw((argc < 2) ? "." : argv[1], disp, 20, flags) == -1) {
perror("nftw");
return -1;
}
printf("\n");
// nftw((argc < 2) ? "." : argv[1], linked, 20, flags);
printll(tmp);
exit(EXIT_SUCCESS);
}
static int disp(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw){
printf("%-3s\t\t%7jd\t\t%-40s\t\t%ld\n",
(typeflag == FTW_D) ? "d" : (typeflag == FTW_F) ? "f": "???",
s->st_size, fpath, s->st_ino);
struct dirent *r;
if(typeflag == FTW_F){ //How to check empty dirs here?
if(head == NULL){
head = malloc(sizeof(node));
head->ino = s->st_ino;
head->f_size = s->st_size;
head->a_tm = s->st_atime;
head->m_tm = s->st_mtime;
head->c_tm = s->st_ctime;
head->next = NULL;
tmp = head;
} else if(head != NULL) {
if(tmp != NULL){
node *ptr = malloc(sizeof(node));
ptr->ino = s->st_ino;
ptr->f_size = s->st_size;
ptr->a_tm = s->st_atime;
ptr->m_tm = s->st_mtime;
ptr->c_tm = s->st_ctime;
ptr->next = NULL;
tmp->next = ptr;
tmp = tmp->next;
}
}
while(tmp != NULL){
printf("%ld\n", tmp->ino);
printf("%ld\n", tmp->f_size);
printf("%ld\n", tmp->a_tm);
printf("%ld\n", tmp->m_tm);
printf("%ld\n", tmp->c_tm);
tmp = tmp->next;
}
}
return 0;
}
void printll(node *head){
node *ptr;
if(head == NULL)
printf("The linked list is NULL\n");
ptr = head;
while(ptr != NULL){
printf("%ld\n", ptr->ino);
printf("%ld\n", ptr->f_size);
printf("%ld\n", ptr->a_tm);
printf("%ld\n", ptr->m_tm);
printf("%ld\n", ptr->c_tm);
ptr = ptr->next;
}
}
Here's the code for creaiting the linked list using ftw
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <libgen.h>
#include <ftw.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
typedef struct node{
long ino;
long f_size;
long a_tm;
long m_tm;
long c_tm;
struct node *next;
}node;
node *c, *tmp = NULL, *loc;
static node *head = NULL;
void printll(node *head); //printing of linked list
static int disp(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw);
static int linked(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw);
void add_at_end(node *p);
/* ------------------Main---------------------*/
int main(int argc, char *argv[]){
int flags = 0;
if(argc > 2 && strchr(argv[2], 'd') != NULL)
flags |= FTW_DEPTH;
printf("File_type\tF_size\t\tPath\t\t\t\t\t\t\tInode\n");
if(nftw((argc < 2) ? "." : argv[1], disp, 20, flags) == -1) {
perror("nftw");
return -1;
}
nftw((argc < 2) ? "." : argv[1], linked, 20, flags);
printf("\n");
printll(tmp);
int num, fd;
char f_name[100], dest[100], str_ent[100];
char c, dl;
struct stat fb;
while(1){
printf("1. Add a file\n");
printf("2. Delete a file\n");
printf("3. Add a directory\n");
printf("4. Delete a directory\n");
printf("Enter the operation num to perform\n");
scanf(" %d", &num);
switch(num){
case 1:
printf("File Name: ");
scanf("%s", f_name);
printf("Destination: ");
scanf("%s", dest);
strcat(dest, f_name);
open(dest, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
printf("File %s is successfully added.\n", f_name);
printf("Do you want to write to this file (Y/N)? \n");
scanf(" %c", &c);
if(c == 'y' || c == 'Y'){
FILE *f;
f = fopen(dest, "w");
printf("How many lines do you want to enter: ");
scanf("%d", &num);
printf("Enter content\n");
for(int i = 0; i < num+1; i++){
fgets(str_ent, sizeof str_ent, stdin);
fputs(str_ent, f);
}
printf("The content you entered is written to the file\n");
fclose(f);
stat(dest, &fb);
loc = malloc(sizeof(node));
loc->ino = fb.st_ino;
loc->f_size = fb.st_size;
loc->a_tm = fb.st_atime;
loc->m_tm = fb.st_mtime;
loc->c_tm = fb.st_ctime;
loc->next = NULL;
node *b;
b = tmp;
while(b->next != NULL)
b = b->next;
b->next = loc;
printf("File added to linked list successfully\n");
break;
} else if( c == 'n' || c == 'N'){
stat(dest, &fb);
loc = malloc(sizeof(node));
loc->ino = fb.st_ino;
loc->f_size = fb.st_size;
loc->a_tm = fb.st_atime;
loc->m_tm = fb.st_mtime;
loc->c_tm = fb.st_ctime;
loc->next = NULL;
node *b;
b = tmp;
while(b->next != NULL)
b = b->next;
b->next = loc;
printf("File added to linked list successfully\n");
free(loc);
break;
}
case 2:
printf("File Name: ");
scanf("%s", f_name);
printf("Destination: ");
scanf("%s", dest);
strcat(dest, f_name);
stat(dest, &fb);
printf("The inode for removed file is: %ld\n", fb.st_ino);
loc = malloc(sizeof(node));
loc->ino = fb.st_ino;
loc->f_size = fb.st_size;
loc->a_tm = fb.st_atime;
loc->m_tm = fb.st_mtime;
loc->c_tm = fb.st_ctime;
loc->next = NULL;
if(loc->ino == tmp->ino){
tmp = tmp->next;
printf("The node is shifted to next and break is here\n");
break;
} else {
node *bu, *cu;
bu = tmp; //tmp
cu = tmp; //tmp2
while(cu->ino != loc->ino){
bu = cu;
cu = cu->next;
}
bu->next = cu->next;
free(cu);
cu = NULL;
unlink(dest);
printf("File %s has been removed & linked list it updated.\n", f_name);
break;
}
case 3:
printf("Dir Name: ");
scanf("%s", f_name);
printf("\nDestination: ");
scanf("%s", dest);
strcat(dest, f_name);
mkdir(dest, 00700);
stat(dest, &fb);
loc = malloc(sizeof(node));
loc->ino = fb.st_ino;
loc->f_size = fb.st_size;
loc->a_tm = fb.st_atime;
loc->m_tm = fb.st_mtime;
loc->c_tm = fb.st_ctime;
loc->next = NULL;
printf("Directory %s successfully added at %s\n", f_name, dest);
break;
case 4:
printf("Dir Name: ");
scanf("%s", f_name);
printf("Destination: ");
scanf("%s", dest);
rmdir(dest);
printf("The directory has been deleted successfully\n");
break;
default:
printf("Operation doesn't exits\n");
exit(0);
}
printf("Do you want to continue with file operations (Y/N)? ");
scanf(" %c", &c);
if(c == 'y' || c == 'Y')
continue;
else
break;
}
while(1){
printf("Do you want to print Director structure OR Linked List (D/L)? ");
scanf(" %c", &dl);
if(dl == 'd' || dl == 'D')
nftw((argc < 2) ? "." : argv[1], disp, 20, flags);
if(dl == 'l' || dl == 'L')
printll(tmp);
printf("Do you want to continue the print? ");
scanf(" %c", &c);
if(c == 'y' || c == 'Y')
continue;
else
break;
}
free(tmp);
exit(EXIT_SUCCESS);
}
/* ----------------Main exit--------------------*/
/* ----------------Display Dir tree structure --------------------*/
static int disp(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw){
printf("%-3s\t\t%7jd\t\t%-40s\t\t%ld\n",
(typeflag == FTW_D) ? "d" : (typeflag == FTW_F) ? "f": "???",
s->st_size, fpath, s->st_ino);
return 0;
}
/* ----------------xx-xx-------------------*/
/* -----------------Linked list function ----------------- */
static int linked(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw){
struct dirent *r;
DIR *d;
int files = 0;
if(typeflag == FTW_D){
d= opendir(fpath);
while((r = readdir(d)) != NULL)
files++;
}
if(typeflag == FTW_F || files == 2){
if(head == NULL){
head = malloc(sizeof(node));
head->ino = s->st_ino;
head->f_size = s->st_size;
head->a_tm = s->st_atime;
head->m_tm = s->st_mtime;
head->c_tm = s->st_ctime;
head->next = NULL;
tmp = head;
} else if(head != NULL) {
node *c = (struct node *)malloc(sizeof(node));
c->ino = s->st_ino;
c->f_size = s->st_size;
c->a_tm = s->st_atime;
c->m_tm = s->st_mtime;
c->c_tm = s->st_ctime;
c->next = NULL;
add_at_end(c);
}
}
return 0;
}
/* ------------------xx-------xx--------------------------- */
/* ---------------function to add at end ---------------- */
void add_at_end(node *p){
node *c2 = (struct node *)malloc(sizeof(node));
c2 = tmp;
while(c2->next != NULL)
c2 = c2->next;
c2->next = p;
}
/* --------------------------x--x-------------------------*/
/* -----------------------Printing linked list ------------------------- */
void printll(node *head){
node *ptr;
if(head == NULL)
printf("The linked list is NULL\n");
ptr = head;
while(ptr != NULL){
printf("%ld\n", ptr->ino);
printf("%ld\n", ptr->f_size);
printf("%ld\n", ptr->a_tm);
printf("%ld\n", ptr->m_tm);
printf("%ld\n", ptr->c_tm);
ptr = ptr->next;
printf("\n");
}
}
/* ------------------------x---x--------------------------------------- */

Memory Leak in Binary Tree Initialize Function

I am attempting to make and evaluate a binary expression tree based on a postfix user input string in C. My binary tree initialization function is causing memory leaks, however. To summarize my algorithm, the user enters a postfix string of input which is parsed through by a function and assembled into the tree. Here's my full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
// Define binary expression tree data structure
typedef struct binExpTree {
char *val;
struct binExpTree *left;
struct binExpTree *right;
} expTree;
// Define expression tree stack data structure
typedef struct expTreeStack {
int height;
int used;
expTree **expTreeDarr;
} treeStack;
// Function prototypes
void initStack(treeStack *stack);
expTree * getTopStack(treeStack *stack);
int isEmptyStack(treeStack *stack);
void pushStack(treeStack *stack, expTree *treeNode);
expTree * popStack(treeStack *stack);
void clearStack(treeStack *stack);
expTree * initTree(char *val);
void printCommands();
expTree * parseExpression(char *expString);
void clearTree(expTree *rootNode);
void printInfix(expTree *rootNode);
void printPrefix(expTree *rootNode);
int evalExpression(expTree *rootNode);
/* File contains all functions necessary for stack operations */
// Initialize empty binary tree stack of size 4
void initStack(treeStack *stack) {
stack->height = 4;
stack->used = 0;
stack->expTreeDarr = (expTree **)malloc(sizeof(expTree *) * stack->height);
}
// Return the tree node from the stack's top
expTree * getTopStack(treeStack *stack) {
if (stack->used > 0) {
return stack->expTreeDarr[stack->used - 1];
}
else {
return NULL;
}
}
// Discern whether tree stack is empty
int isEmptyStack(treeStack *stack) {
if (stack->used == 0) {
return TRUE;
}
else {
return FALSE;
}
}
// Push tree node pointer onto stack
void pushStack(treeStack *stack, expTree *treeNode) {
if (stack->used == stack->height) {
expTree **expTreeTmp = stack->expTreeDarr;
stack->height += 4;
stack->expTreeDarr = (expTree **)malloc(sizeof(expTree *) * stack->height);
for (int i = 0; i < stack->used; i++) {
stack->expTreeDarr[i] = expTreeTmp[i];
//free(expTreeTmp[i]);
}
free(expTreeTmp);
}
stack->expTreeDarr[stack->used] = treeNode;
stack->used = stack->used + 1;
}
// Pop tree node pointer from the stack
expTree * popStack(treeStack *stack) {
expTree *stackTmp = getTopStack(stack);
expTree *newNode = (expTree *)malloc(sizeof(expTree));
*newNode = *stackTmp;
stack->used -= 1;
return newNode;
}
// Empty stack of all data (make sure this works)
void clearStack(treeStack *stack) {
for (int i = 0; i < stack->used; i++) {
clearTree(stack->expTreeDarr[i]);
}
free(stack->expTreeDarr);
stack->used = 0;
stack->height = 0;
}
/* File contains all functions necessary for binary tree operations */
// Initialize binary expression tree with specified operator/operand
expTree * initTree(char *val) {
expTree *newTree = (expTree *)malloc(sizeof(expTree));
newTree->val = (char *)malloc(strlen(val) + 1);
strcpy(newTree->val, val);
newTree->left = NULL;
newTree->right = NULL;
return newTree;
}
// Print commands available to the user
void printCommands() {
printf("The commands for this program are:\n\n");
printf("q - to quit the program\n");
printf("? - to list the accepted commands\n");
printf("or any postfix mathematical expression using the operators of *, /, +, -\n");
}
// Return size of binary expression tree
int sizeTree(expTree *treeNode) {
if (treeNode == NULL) {
return 0;
}
else {
return 1 + sizeTree(treeNode->left) + sizeTree(treeNode->right);
}
}
// Construct a postfix binary expression tree from expression string
expTree * parseExpression(char *expString) {
char *expStringCopy = (char *)malloc(strlen(expString) + 1);
expTree *treeNode;
treeStack expStack;
initStack(&expStack);
strcpy(expStringCopy, expString);
char *expStringTok = strtok(expStringCopy, " ");
while (expStringTok != NULL) {
if (*expStringTok == '+' || *expStringTok == '-' ||
*expStringTok == '*' || *expStringTok == '/') {
if (expStack.used < 2) {
return NULL;
}
treeNode = initTree(expStringTok);
treeNode->right = popStack(&expStack);
treeNode->left = popStack(&expStack);
pushStack(&expStack, treeNode);
}
else {
treeNode = initTree(expStringTok);
pushStack(&expStack, treeNode);
}
expStringTok = strtok(NULL, " ");
}
if (expStack.used > 1 || (*(treeNode->val) != '+' && *(treeNode->val) != '-' &&
*(treeNode->val) != '*' && *(treeNode->val) != '/')) {
return NULL;
}
free(expStringCopy);
treeNode = popStack(&expStack);
clearStack(&expStack);
return treeNode;
}
// Clear binary expression tree
void clearTree(expTree *rootNode) {
if (rootNode == NULL) {
return;
}
else {
clearTree(rootNode->left);
clearTree(rootNode->right);
free(rootNode->val);
free(rootNode);
}
}
// Print infix notation of expression
void printInfix(expTree *rootNode) {
if (rootNode == NULL) {
return;
}
else {
if (*(rootNode->val) == '+' || *(rootNode->val) == '-' ||
*(rootNode->val) == '*' || *(rootNode->val) == '/') {
printf("( ");
}
printInfix(rootNode->left);
printf(" %s ", rootNode->val);
printInfix(rootNode->right);
if (*(rootNode->val) == '+' || *(rootNode->val) == '-' ||
*(rootNode->val) == '*' || *(rootNode->val) == '/') {
printf(" )");
}
}
}
// Print prefix notation of expression
void printPrefix(expTree *rootNode) {
if (rootNode == NULL) {
return;
}
else {
printf(" %s ", rootNode->val);
printPrefix(rootNode->left);
printPrefix(rootNode->right);
}
}
// Evaluate the expression tree
int evalExpression(expTree *rootNode) {
char op;
if (*(rootNode->val) == '+') {
return evalExpression(rootNode->left) + evalExpression(rootNode->right);
}
else if (*(rootNode->val) == '-') {
return evalExpression(rootNode->left) - evalExpression(rootNode->right);
}
else if (*(rootNode->val) == '*') {
return evalExpression(rootNode->left) * evalExpression(rootNode->right);
}
else if (*(rootNode->val) == '/') {
return evalExpression(rootNode->left) / evalExpression(rootNode->right);
}
else {
return atoi(rootNode->val);
}
}
int main(int argc, char const *argv[])
{
char input[300];
expTree *expPostfix;
/* set up an infinite loop */
while (1)
{
fgets(input,300,stdin);
/* remove the newline character from the input */
int i = 0;
while (input[i] != '\n' && input[i] != '\0') {
i++;
}
input[i] = '\0';
/* check if user enter q or Q to quit program */
if ( (strcmp (input, "q") == 0) || (strcmp (input, "Q") == 0) )
break;
/* check if user enter ? to see command list */
else if ( strcmp (input, "?") == 0)
printCommands();
/* user enters an expression */
else {
// Parse the expression into a binary expression tree
printf("%s\n", input);
expPostfix = parseExpression(input);
// Discern whether expression is valid
if (expPostfix == NULL) {
printf("Invalid expression. Enter a valid postfix expression \n");
continue;
}
// Print the expression in infix notation
printf("Infix notation: ");
printInfix(expPostfix);
printf("\n");
// Print the expression in prefix notation
printf("Prefix notation: ");
printPrefix(expPostfix);
printf("\n");
// Print the expression in postfix notation
printf("Postfix notation: ");
printf("%s\n", input);
// Evaluate expression and print result
printf("Expression result: %d \n\n", evalExpression(expPostfix));
clearTree(expPostfix);
}
}
printf("\nGoodbye\n");
return 0;
}
Upon running with Valgrind and an input of "1 1 -", this is the output:
==35604==
==35604== HEAP SUMMARY:
==35604== in use at exit: 72 bytes in 3 blocks
==35604== total heap usage: 13 allocs, 10 frees, 2,236 bytes allocated
==35604==
==35604== 24 bytes in 1 blocks are definitely lost in loss record 1 of 2
==35604== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==35604== by 0x10952C: initTree (proj4base_38.c:143)
==35604== by 0x1096CC: parseExpression (proj4base_38.c:194)
==35604== by 0x109B8A: main (proj4base_38.c:323)
==35604==
==35604== 48 bytes in 2 blocks are definitely lost in loss record 2 of 2
==35604== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==35604== by 0x10952C: initTree (proj4base_38.c:143)
==35604== by 0x109719: parseExpression (proj4base_38.c:201)
==35604== by 0x109B8A: main (proj4base_38.c:323)
==35604==
==35604== LEAK SUMMARY:
==35604== definitely lost: 72 bytes in 3 blocks
==35604== indirectly lost: 0 bytes in 0 blocks
==35604== possibly lost: 0 bytes in 0 blocks
==35604== still reachable: 0 bytes in 0 blocks
==35604== suppressed: 0 bytes in 0 blocks
==35604==
==35604== For lists of detected and suppressed errors, rerun with: -s
==35604== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
So it seems the culprit is my initTree() function. However, I just cannot wrap my head around why this memory is being lost. I hope this isn't too much code. This is an edit from previously, where someone informed me there was not enough information to go on.
The leak is caused by popStack, because the target of stackTmp gets leaked when the function exits:
expTree * popStack(treeStack *stack) {
expTree *stackTmp = getTopStack(stack);
expTree *newNode = (expTree *)malloc(sizeof(expTree));
*newNode = *stackTmp;
stack->used -= 1;
return newNode;
}
Given that the stack seemed to be the exclusive owner of the tree, and it no longer has a pointer to it, popStack can avoid the leak by simply not making a copy and returning the original:
expTree * popStack(treeStack *stack) {
expTree *topNode = getTopStack(stack);
stack->used -= 1;
return topNode;
}

Rot13 implementation: error in translate_string function

I wrote a rot13.c program but I can tell something in my loop inside rot13_translate_string is causing the program to just print out blank lines.
Any thoughts?
Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char rot13_translate_character(char c)
{
if( 'A' <= c && c <= 'M' )
{
return c + 13;
}
else if( 'N' <= c && c <= 'Z' )
{
return c - 13;
}
else if( 'a' <= c && c <= 'm' )
{
return c + 13;
}
else if( 'n' <= c && c <= 'z' )
{
return c - 13;
}
else
{
return c;
}
}
char *rot13_translate_string(const char *str)
{
int len = strlen(str);
char *translation = calloc(len, sizeof(char));
int i;
do //****HERE IN THIS SECTION
{
/* Translate each character, starting from the end of the string. */
translation[len] = rot13_translate_character(str[len]);
len--;
} while( len < 0 ); //<
return translation;
}
And here is the main (part of the same file) - is the condition for my for i = 1 ok?
int main(int argc, char **argv)
{
if( argc < 2)
{
fprintf(stderr, "Usage: %s word [word ...]\n", argv[0]);
return 1;
}
/* Translate each of the arguments */
int i;
for( i = 1; i < argc; i++) //*****IS this right?
{
char *translation = rot13_translate_string( argv[i] );
fprintf(stdout, "%s\n", translation);
}
return 0;
}
As just it was pointed out by Janis is the control on the loop do ... while. It should be
while( len >= 0 );
A "while" loop runs while the control expression is true (and terminates once the expression becomes false). You define the variable len just before the loop and it cannot be <0.
So you never really enter in the loop.
You obtain a line for each input word because of fprintf(stdout, "%s\n", translation); line, where you print for each (empty) word a line (\n).
In other languages, for example in Pascal, there is "repeat until" loop construction, which continues to run until the control expression is true, and only after that it changes it terminates.
In that case you could use a condition with <0.
In C to follow the same logic you can use while loop and negate the condition. In your case
} while (! (len < 0) );

(HW) Pallindrom using Stack and Queue, Run Time Error

Alright, i have a hw assignment to check if an inserted string is a palindrome. The string must first be inserted into a stack, a queue, and then compared. I have the program up and running, for me that is. My teacher, when trying to grade it experience(d) a run time error. Also, getline portable is a requirement of the assignment and came with the file and instructions.
This is the note from the teacher:
Check if a line is a palindrome. Ignore spaces? y/n y (her running the code)
Input line to check
(where she gets the runtime error)
175 [main] csc240Summer2014PE8Student 10060 open_stackdumpfile: Dumping stack trace to csc240Summer2014PE8Student.exe.stackdump
#include <iostream>
#include <stack>
#include <queue>
#include <string>
using namespace std;
istream& getline_portable( istream& is, string& str ) {
istream& ris = std::getline(is,str);
if ( str.size() && str[str.size()-1] == '\r' )
str.resize(str.size()-1);
return ris;
}
int main()
{
stack<char> s;
queue<char> q;
char c, choice, b;
string str;
int i = 0;
int count = 0;
do
{
cout<<"Check if a line is a palindrome. Ignore spaces? y/n ";
cin >> b;
cin.ignore();
tolower(b);
cout<<"Input line to check\n";
getline_portable(cin,str);
for(int j = 0; j < str.size(); j++)
str[j] = tolower(str[j]);
if(b == 'n')
{
for(int j = 0; j < str.size(); j++)
{
c = str[j];
q.push(c);
s.push(c);
}
}
else if (b == 'y')
{
for(int j = 0; j < str.size() - count; j++)
{
c = str[j];
if(isspace(c))
{
}
else if(!isspace(c))
{
q.push(c);
s.push(c);
}
}
}
do
{
if(q.front() != s.top())
{
i = false;
break;
}
else
{
i = true;
s.pop();
q.pop();
}
}while(!q.empty() && !s.empty());
if (i == true)
cout << str << " is a pallindrom.\n";
else if (i == false)
cout << "Your input of " << str << " is not a pallindrome.\n";
cout << "Would you like to test another string? y/n ";
cin >> choice;
tolower(choice);
cin.ignore();
}while (choice == 'y');
cout << "Press enter to continue...";
cin.get();
return 0;
}

OpenCV load image/video from stdin

I am trying to read a jpg image from stdin using the following code:
int c,count=0;
vector<uchar> buffer; //buffer for coding
/* for stdin, we need to read in the entire stream until EOF */
while ((c = fgetc(stdin)) != EOF) {
buffer.push_back(c);
count++;
}
cout << "Bytes: " << count << endl;
Mat im = imdecode(Mat(buffer),CV_LOAD_IMAGE_COLOR);
cout << "Decoded\n";
namedWindow("image", CV_WINDOW_AUTOSIZE);
imshow("image",im);
cv::waitKey(0);
I run this in cmd:
OpenCVTest < thumb.jpg
This is what I get:
Bytes: 335
Decoded
OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or unsupported array type) in unknown function, file ..\..\..\src\opencv\modules\core\src\array.cpp, line 2482
The error seems reasonable since the image is about 7 KB and but according to the counter only 335 bytes have been read.
What am I doing wrong ?
My ultimate goal is to read a video from stdin frame by frame. Would that be possible ?
Thank you very much !
the following reads a jpeg sequence from stdin frame by frame. examples:
ffmpeg
ffmpeg -i input.mp4 -vcodec mjpeg -f image2pipe -pix_fmt yuvj420p -r 10 -|program.exe
mencoder
mencoder input.mp4 -nosound -ovc lavc -lavcopts vcodec=mjpeg -o -|program.exe
curl
curl "http://10.10.201.241/mjpeg/video.cgi&resolution=320x240"|program.exe
code
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
#if defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) \
|| defined(WIN64) || defined(_WIN64) || defined(__WIN64__)
# include <io.h>
# include <fcntl.h>
# define SET_BINARY_MODE(handle) setmode(handle, O_BINARY)
#else
# define SET_BINARY_MODE(handle) ((void)0)
#endif
#define BUFSIZE 10240
int main ( int argc, char **argv )
{
SET_BINARY_MODE(fileno(stdin));
std::vector<char> data;
bool skip=true;
bool imgready=false;
bool ff=false;
int readbytes=-1;
while (1)
{
char ca[BUFSIZE];
uchar c;
if (readbytes!=0)
{
readbytes=read(fileno(stdin),ca,BUFSIZE);
for(int i=0;i<readbytes;i++)
{
c=ca[i];
if(ff && c==(uchar)0xd8)
{
skip=false;
data.push_back((uchar)0xff);
}
if(ff && c==0xd9)
{
imgready=true;
data.push_back((uchar)0xd9);
skip=true;
}
ff=c==0xff;
if(!skip)
{
data.push_back(c);
}
if(imgready)
{
if(data.size()!=0)
{
cv::Mat data_mat(data);
cv::Mat frame(imdecode(data_mat,1));
imshow("frame",frame);
waitKey(1);
}else
{
printf("warning");
}
imgready=false;
skip=true;
data.clear();
}
}
}
else
{
throw std::string("zero byte read");
}
}
}

Resources