My code is like a text compressor, reading normal text and turns into numbers, every word has a number. It compiles in DevC++ but does not end, however, it does not compile in Ubuntu 13.10. I'm getting an error like in the title in Ubuntu "undefined reference to `strlwr'", my code is a little long so I am not able to post it here, but one of the error is from here:
//operatinal funcitons here
int main()
{
int i = 0, select;
char filename[50], textword[40], find[20], insert[20], delete[20];
FILE *fp, *fp2, *fp3;
printf("Enter the file name: ");
fflush(stdout);
scanf("%s", filename);
fp = fopen(filename, "r");
fp2 = fopen("text.txt", "w+");
while (fp == NULL)
{
printf("Wrong file name, please enter file name again: ");
fflush(stdout);
scanf("%s", filename);
fp = fopen(filename, "r");
}
while (!feof(fp))
{
while(fscanf(fp, "%s", textword) == 1)
{
strlwr(textword);
//some other logic
}
}
.... //main continues
strlwr() is not standard C function. Probably it's provided by one implementation while the other compiler you use don't.
You can easily implement it yourself:
#include <string.h>
#include<ctype.h>
char *strlwr(char *str)
{
unsigned char *p = (unsigned char *)str;
while (*p) {
*p = tolower((unsigned char)*p);
p++;
}
return str;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strlwr(char* );
int main()
{
printf("Please Enter Size Of The String: \n");
int a,b;
scanf("%d",&a);
char* str;
str=(char*)malloc(sizeof(char)*a);
scanf("\n%[^\n]",str);
char* x;
x=strlwr(str);
for(b=0;x[b]!='\0';b++)
{
printf("%c",x[b]);
}
free(str);
return 0;
}
char* strlwr(char* x)
{
int b;
for(b=0;x[b]!='\0';b++)
{
if(x[b]>='A'&&x[b]<='Z')
{
x[b]=x[b]-'A'+'a';
}
}
return x;
}
Related
I'm reading file using fread().[read file only]
On compilation, the compiler throws a "Segmentation fault (core dumped)" error.
I'm using structure.
I wrote this code.
type #include <string.h>
#include <stdio.h>
#include <stdlib.h>
int twilio_send_functionapi(char *channel, char *status); // function declartion
struct credentials
{
char *account_sid;
char *auth_token;
char *from_number;
char *to_number;
} c1;
int main(int argc, char *argv[])
{
FILE *fp;
struct credentials input;
fp = fopen("data.config", "r");
if (fp == NULL)
{
printf("Error\n");
return -1;
}
dentials.to_number = (char*)malloc(sizeof(char)*100);
while(fread(&c1,sizeof(struct credentials),1 ,fp))
fscanf(fp,"%s %s %s %s", c1.account_sid, c1.auth_token,c1.from_number, c1.to_number);
char *channel,*status;
channel = argv[1];
status = argv[2];
twilio_send_functionapi(channel,status); //function call
}
Don't know where I'm mistaken.
here is .conf file which needs to be read
account_sid : AC40cfb4f3e98b55b13a9b93527683171e
auth_token : 5f6906d7847ad1fc1fc1170ab60e40fd
from_number : 15867854760
to_number : 1212321123
Instead of fread(), fscanf(), use fgets() to read a line of the file into a string.
// 123456789 123456789 123456789 123456789
//account_sid : AC40cfb4f3e98b55b13a9b93527683171e
#define SID_LEN 34
struct credentials {
char account_sid[SID_LEN + 1]; // Use array here, not pointer.
// ... omitted for brevity
} c1;
#define LINE_SIZE 100
char line[LINE_SIZE];
if (fgets(line, sizeof line, fp)) {
if (sscanf(line, "account_sid : %34s", c1.account_sid) == 1) {
; // Success
} else {
; // Failed
}
Continue likewise for the other c1 members`.
Thank you everyone.
I resolve my problem.
char credential[4][100] ;
int main()
{
FILE *fp;
fp = fopen("data.config", "r");
if (fp == NULL)
{
printf("Error\n");
return -1;
}
printf("File is opened\n");
if ((fscanf(fp,"account_sid-%s\n",credential[0])!= 1))
{
printf("error reading account_sid value\n");
return -1;
}
fclose(fp);
}
I get the above error in CppCheck but I can't see what's wrong.I guess the error is the reason my code doesn't find any files,even if they exist in my computer.Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 80
char *getchoice(void);
void getfile(char *filename);
int main() {
char *choice;
choice=getchoice();
getfile(choice);
return 0;
}
char *getchoice(void) {
char *filename;
filename=malloc(SIZE);
printf("Enter the name of the text file: ");
scanf("%30s",filename);
return filename;
}
void getfile(char *filename) {
FILE *fp;
fp=fopen(filename,"r");
if (fp==NULL){
printf("The entered file does not exist.");
printf("\n");
}
else{
printf("The file exists.");
}
fclose(fp);
return;
}
Here is a list of things to do, in order to clean up this program:
Handle the event that malloc fails, so that scanf and getfile are not passed NULL.
Check that scanf successfully performed the expected number of conversions, to ensure filename contains valid data.
Use perror to give more accurate information about why malloc or fopen failed.
Avoid passing NULL to fclose, in the event that fopen failed.
free memory allocated by malloc (Unlike fclose, free may be safely passed NULL).
#include <stdio.h>
#include <stdlib.h>
char *getchoice(void);
void getfile(char *filename);
int main(void) {
char *choice = getchoice();
if (choice)
getfile(choice);
free(choice);
}
char *getchoice(void) {
char *filename = malloc(80);
if (filename) {
printf("Enter the name of the text file: ");
if (1 != scanf("%79s", filename)) {
free(filename);
return NULL;
}
} else {
perror("malloc");
}
return filename;
}
void getfile(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp) {
puts("File opened.");
fclose(fp);
} else {
perror("fopen");
}
}
I'm trying to create something where I need to receive a sentence from the user and it is then written in a text file. I know how to do this with integers and float but it doesn't seem to work with char.
main()
{
unsigned char word;
FILE *f;
errno_t err;
printf("Enter Text: ");
scanf_s("%c", &word);
err = fopen_s(&f, "testwrite.txt", "w");
fprintf_s(f, "%c", word);
fclose(f);
return 0;
}
to get input from the user:
char input[1000];
scanf("%s", input);
and to write it to a file:
fputc(input, f);
and the final piece code should look like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[1000];
FILE *f;
f = fopen(fileName ,"w+");
printf("enter text:");
scanf("%s", input);
fputc(input, f);
fclose(f);
return 0;
}
I must modify my program to accept input from
a file called anagrams.txt.This file should have two strings per line, separated by the # character. My program should read
each pair of strings and report back if each pair of strings is an anagram. For example consider the following content of anagrams.txt:
hello#elloh
man#nam
Astro#Oastrrasd
Your program should print out the following:
hello#elloh - Anagrams!
man#nam - Anagrams!
Astro#Oastrrasd- Not anagrams!
I should compile in g++
Here is the code to read from text:
int main()
{
char input[30];
if(access( "anagrams.txt", F_OK ) != -1) {
FILE *ptr_file;
char buf[1000];
ptr_file =fopen("anagrams.txt","r"); if (!ptr_file)
return 1;
while (fgets(buf,1000, ptr_file)!=NULL)
printf("%s",buf);
fclose(ptr_file);
printf("\n");
}
else{ //if file does not exist
printf("\nFile not found!\n");
}
return 0;
}
Code to find if the text are anagrams:
#include <stdio.h>
int find_anagram(char [], char []);
int main()
{
char array1[100], array2[100];
int flag;
printf("Enter the string\n");
gets(array1);
printf("Enter another string\n");
gets(array2);
flag = find_anagram(array1, array2);
if (flag == 1)
printf(" %s and %s are anagrams.\n", array1, array2);
else
printf("%s and %s are not anagrams.\n", array1, array2);
return 0;
}
int find_anagram(char array1[], char array2[])
{
int num1[26] = {0}, num2[26] = {0}, i = 0;
while (array1[i] != '\0')
{
num1[array1[i] - 'a']++;
i++;
}
i = 0;
while (array2[i] != '\0')
{
num2[array2[i] -'a']++;
i++;
}
for (i = 0; i < 26; i++)
{
if (num1[i] != num2[i])
return 0;
}
return 1;
}
You can try something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXLINE 1000
#define MAXLETTER 256
int is_anagram(char *word1, char *word2);
void check_lines(FILE *filename);
int cmpfunc(const void *a, const void *b);
void convert_to_lowercase(char *word);
int
main(int argc, char const *argv[]) {
FILE *filename;
if ((filename = fopen("anagram.txt", "r")) == NULL) {
fprintf(stderr, "Error opening file\n");
exit(EXIT_FAILURE);
}
check_lines(filename);
fclose(filename);
return 0;
}
void
check_lines(FILE *filename) {
char line[MAXLINE];
char *word1, *word2, *copy1, *copy2;
while (fgets(line, MAXLINE, filename) != NULL) {
word1 = strtok(line, "#");
word2 = strtok(NULL, "\n");
copy1 = strdup(word1);
copy2 = strdup(word2);
convert_to_lowercase(copy1);
convert_to_lowercase(copy2);
if (is_anagram(copy1, copy2)) {
printf("%s#%s - Anagrams!\n", word1, word2);
} else {
printf("%s#%s - Not Anagrams!\n", word1, word2);
}
}
}
void
convert_to_lowercase(char *word) {
int i;
for (i = 0; word[i] != '\0'; i++) {
word[i] = tolower(word[i]);
}
}
int
is_anagram(char *word1, char *word2) {
qsort(word1, strlen(word1), sizeof(*word1), cmpfunc);
qsort(word2, strlen(word2), sizeof(*word2), cmpfunc);
if (strcmp(word1, word2) == 0) {
return 1;
}
return 0;
}
int
cmpfunc(const void *a, const void *b) {
if ((*(char*)a) < (*(char*)b)) {
return -1;
}
if ((*(char*)a) > (*(char*)b)) {
return +1;
}
return 0;
}
Since this looks like a University question, I won't provide a full solution, only a hint.
All you have to do is replace the stdin input part of the anagram-finding file with the code you wrote to read from a file: it's as simple as changing
printf("Enter the string\n");
gets(array1);
printf("Enter another string\n");
gets(array2);
to
// before program:
#define SIZE 1000
// inside main
if (access("anagrams.txt", F_OK) == -1){
printf("\nFile not found!\n");
return 1; // Abort the program early if we can't find the file
}
FILE *ptr_file;
char buf[1000];
ptr_file = fopen("anagrams.txt","r");
if (!ptr_file)
return 1;
char array1[SIZE], array2[SIZE];
while (fgets(buf, 1000, ptr_file)!=NULL){
// do all your anagram stuff here!
// there is currently one line of the input file stored in buf
// Hint: You need to split buf into array_1 and array_2 using '#' to separate it.
}
fclose(ptr_file);
printf("\n");
Additional comments:
Don't ever ever ever use gets. gets doesn't check that the string it writes to can hold the data, which will cause your program to crash if it gets input bigger than the array size. Use fgets(buf, BUF_SIZE, stdin) instead.
Beautiful code is good code. People are more likely to help if they can read your code easily. (fix your brackets)
Just for interest, a more efficient algorithm for checking anagrams is to use qsort to sort both arrays, then a simple string matcher to compare them. This will have cost O(mnlog(m+n)), as opposed to O(m^2 n^2), awith the current algorithm
You need to split every line you read by fgets (as you did) in to two strings, and pass them to your find_anagram function. You can do that using strtok:
int main()
{
int flag;
char buf[1000];
FILE *ptr_file;
//Check file existence
//Open the file for reading
while (fgets (buf, 1000, ptr_file) != NULL)
{
char *array1 = strtok(buf, "#");
char *array2 = strtok(NULL, "\n");
flag = find_anagram (array1, array2);
//Check flag value to print your message
}
return 0;
}
//put your find_anagram function
Don't forget to #include <string.h> to use strtok().
I'm trying to find if a record exists on a binary file by searching for a name.
Seems I'm not doing something right since the return of my "if" no matter the input it's always found when it doesn't exist.
The debugger states "if = A syntax error in expression", I'm not seeing it.
#ifndef DATA_PLAYER_H_INCLUDED
#define DATA_PLAYER_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Player
{
char nome[50];
int pontos;
}Players;
void ViewPont();
void SearchPont();
#endif // DATA_PLAYER_H_INCLUDED
--
#include "DATA_PLAYER.h"
void ViewPont()
{
Players pl;
FILE *fp;
int i, pontos;
fp = fopen("Pontuacoes.dat", "rb+");
while((fread(&pl, sizeof(Players),1, fp)) != 0 )
{
printf("%s %d\n", pl.nome, pl.pontos);
}
fclose(fp);
}
void SearchPont()
{
char nam[50];
char ch;
Players pl;
FILE * fp;
fp = fopen("Pontuacoes.dat","rb+");
printf("\n nome das pont\n");
fflush(stdout);
scanf("%s", nam);
printf("%s", nam);
while((fread(&pl, sizeof(Players),1, fp)) != 0)
{
if((strcmp(pl.nome, nam))==0);
{
printf("\nregisto encontrado\n");
}
}
fclose(fp);
}
Silly me..........
if(strcmp(pl.nome, nam) ==0);
-> ; that little detail....
if(strcmp(pl.nome, nam) ==0)